laya.d3.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202
  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. class Vector2 {
  24. constructor(x = 0, y = 0) {
  25. this.x = x;
  26. this.y = y;
  27. }
  28. setValue(x, y) {
  29. this.x = x;
  30. this.y = y;
  31. }
  32. static scale(a, b, out) {
  33. out.x = a.x * b;
  34. out.y = a.y * b;
  35. }
  36. fromArray(array, offset = 0) {
  37. this.x = array[offset + 0];
  38. this.y = array[offset + 1];
  39. }
  40. cloneTo(destObject) {
  41. var destVector2 = destObject;
  42. destVector2.x = this.x;
  43. destVector2.y = this.y;
  44. }
  45. static dot(a, b) {
  46. return (a.x * b.x) + (a.y * b.y);
  47. }
  48. static normalize(s, out) {
  49. var x = s.x, y = s.y;
  50. var len = x * x + y * y;
  51. if (len > 0) {
  52. len = 1 / Math.sqrt(len);
  53. out.x = x * len;
  54. out.y = y * len;
  55. }
  56. }
  57. static scalarLength(a) {
  58. var x = a.x, y = a.y;
  59. return Math.sqrt(x * x + y * y);
  60. }
  61. clone() {
  62. var destVector2 = new Vector2();
  63. this.cloneTo(destVector2);
  64. return destVector2;
  65. }
  66. forNativeElement(nativeElements = null) {
  67. if (nativeElements) {
  68. this.elements = nativeElements;
  69. this.elements[0] = this.x;
  70. this.elements[1] = this.y;
  71. }
  72. else {
  73. this.elements = new Float32Array([this.x, this.y]);
  74. }
  75. Vector2.rewriteNumProperty(this, "x", 0);
  76. Vector2.rewriteNumProperty(this, "y", 1);
  77. }
  78. static rewriteNumProperty(proto, name, index) {
  79. Object["defineProperty"](proto, name, {
  80. "get": function () {
  81. return this.elements[index];
  82. },
  83. "set": function (v) {
  84. this.elements[index] = v;
  85. }
  86. });
  87. }
  88. }
  89. Vector2.ZERO = new Vector2(0.0, 0.0);
  90. Vector2.ONE = new Vector2(1.0, 1.0);
  91. class Vector4 {
  92. constructor(x = 0, y = 0, z = 0, w = 0) {
  93. this.x = x;
  94. this.y = y;
  95. this.z = z;
  96. this.w = w;
  97. }
  98. setValue(x, y, z, w) {
  99. this.x = x;
  100. this.y = y;
  101. this.z = z;
  102. this.w = w;
  103. }
  104. fromArray(array, offset = 0) {
  105. this.x = array[offset + 0];
  106. this.y = array[offset + 1];
  107. this.z = array[offset + 2];
  108. this.w = array[offset + 3];
  109. }
  110. cloneTo(destObject) {
  111. var destVector4 = destObject;
  112. destVector4.x = this.x;
  113. destVector4.y = this.y;
  114. destVector4.z = this.z;
  115. destVector4.w = this.w;
  116. }
  117. clone() {
  118. var destVector4 = new Vector4();
  119. this.cloneTo(destVector4);
  120. return destVector4;
  121. }
  122. static lerp(a, b, t, out) {
  123. var ax = a.x, ay = a.y, az = a.z, aw = a.w;
  124. out.x = ax + t * (b.x - ax);
  125. out.y = ay + t * (b.y - ay);
  126. out.z = az + t * (b.z - az);
  127. out.w = aw + t * (b.w - aw);
  128. }
  129. static transformByM4x4(vector4, m4x4, out) {
  130. var vx = vector4.x;
  131. var vy = vector4.y;
  132. var vz = vector4.z;
  133. var vw = vector4.w;
  134. var me = m4x4.elements;
  135. out.x = vx * me[0] + vy * me[4] + vz * me[8] + vw * me[12];
  136. out.y = vx * me[1] + vy * me[5] + vz * me[9] + vw * me[13];
  137. out.z = vx * me[2] + vy * me[6] + vz * me[10] + vw * me[14];
  138. out.w = vx * me[3] + vy * me[7] + vz * me[11] + vw * me[15];
  139. }
  140. static equals(a, b) {
  141. 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));
  142. }
  143. length() {
  144. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  145. }
  146. lengthSquared() {
  147. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  148. }
  149. static normalize(s, out) {
  150. var len = s.length();
  151. if (len > 0) {
  152. out.x = s.x * len;
  153. out.y = s.y * len;
  154. out.z = s.z * len;
  155. out.w = s.w * len;
  156. }
  157. }
  158. static add(a, b, out) {
  159. out.x = a.x + b.x;
  160. out.y = a.y + b.y;
  161. out.z = a.z + b.z;
  162. out.w = a.w + b.w;
  163. }
  164. static subtract(a, b, out) {
  165. out.x = a.x - b.x;
  166. out.y = a.y - b.y;
  167. out.z = a.z - b.z;
  168. out.w = a.w - b.w;
  169. }
  170. static multiply(a, b, out) {
  171. out.x = a.x * b.x;
  172. out.y = a.y * b.y;
  173. out.z = a.z * b.z;
  174. out.w = a.w * b.w;
  175. }
  176. static scale(a, b, out) {
  177. out.x = a.x * b;
  178. out.y = a.y * b;
  179. out.z = a.z * b;
  180. out.w = a.w * b;
  181. }
  182. static Clamp(value, min, max, out) {
  183. var x = value.x;
  184. var y = value.y;
  185. var z = value.z;
  186. var w = value.w;
  187. var mineX = min.x;
  188. var mineY = min.y;
  189. var mineZ = min.z;
  190. var mineW = min.w;
  191. var maxeX = max.x;
  192. var maxeY = max.y;
  193. var maxeZ = max.z;
  194. var maxeW = max.w;
  195. x = (x > maxeX) ? maxeX : x;
  196. x = (x < mineX) ? mineX : x;
  197. y = (y > maxeY) ? maxeY : y;
  198. y = (y < mineY) ? mineY : y;
  199. z = (z > maxeZ) ? maxeZ : z;
  200. z = (z < mineZ) ? mineZ : z;
  201. w = (w > maxeW) ? maxeW : w;
  202. w = (w < mineW) ? mineW : w;
  203. out.x = x;
  204. out.y = y;
  205. out.z = z;
  206. out.w = w;
  207. }
  208. static distanceSquared(value1, value2) {
  209. var x = value1.x - value2.x;
  210. var y = value1.y - value2.y;
  211. var z = value1.z - value2.z;
  212. var w = value1.w - value2.w;
  213. return (x * x) + (y * y) + (z * z) + (w * w);
  214. }
  215. static distance(value1, value2) {
  216. var x = value1.x - value2.x;
  217. var y = value1.y - value2.y;
  218. var z = value1.z - value2.z;
  219. var w = value1.w - value2.w;
  220. return Math.sqrt((x * x) + (y * y) + (z * z) + (w * w));
  221. }
  222. static dot(a, b) {
  223. return (a.x * b.x) + (a.y * b.y) + (a.z * b.z) + (a.w * b.w);
  224. }
  225. static min(a, b, out) {
  226. out.x = Math.min(a.x, b.x);
  227. out.y = Math.min(a.y, b.y);
  228. out.z = Math.min(a.z, b.z);
  229. out.w = Math.min(a.w, b.w);
  230. }
  231. static max(a, b, out) {
  232. out.x = Math.max(a.x, b.x);
  233. out.y = Math.max(a.y, b.y);
  234. out.z = Math.max(a.z, b.z);
  235. out.w = Math.max(a.w, b.w);
  236. }
  237. forNativeElement(nativeElements = null) {
  238. if (nativeElements) {
  239. this.elements = nativeElements;
  240. this.elements[0] = this.x;
  241. this.elements[1] = this.y;
  242. this.elements[2] = this.z;
  243. this.elements[3] = this.w;
  244. }
  245. else {
  246. this.elements = new Float32Array([this.x, this.y, this.z, this.w]);
  247. }
  248. Vector2.rewriteNumProperty(this, "x", 0);
  249. Vector2.rewriteNumProperty(this, "y", 1);
  250. Vector2.rewriteNumProperty(this, "z", 2);
  251. Vector2.rewriteNumProperty(this, "w", 3);
  252. }
  253. }
  254. Vector4.ZERO = new Vector4();
  255. Vector4.ONE = new Vector4(1.0, 1.0, 1.0, 1.0);
  256. Vector4.UnitX = new Vector4(1.0, 0.0, 0.0, 0.0);
  257. Vector4.UnitY = new Vector4(0.0, 1.0, 0.0, 0.0);
  258. Vector4.UnitZ = new Vector4(0.0, 0.0, 1.0, 0.0);
  259. Vector4.UnitW = new Vector4(0.0, 0.0, 0.0, 1.0);
  260. class Vector3 {
  261. constructor(x = 0, y = 0, z = 0, nativeElements = null) {
  262. this.x = x;
  263. this.y = y;
  264. this.z = z;
  265. }
  266. static distanceSquared(value1, value2) {
  267. var x = value1.x - value2.x;
  268. var y = value1.y - value2.y;
  269. var z = value1.z - value2.z;
  270. return (x * x) + (y * y) + (z * z);
  271. }
  272. static distance(value1, value2) {
  273. var x = value1.x - value2.x;
  274. var y = value1.y - value2.y;
  275. var z = value1.z - value2.z;
  276. return Math.sqrt((x * x) + (y * y) + (z * z));
  277. }
  278. static min(a, b, out) {
  279. out.x = Math.min(a.x, b.x);
  280. out.y = Math.min(a.y, b.y);
  281. out.z = Math.min(a.z, b.z);
  282. }
  283. static max(a, b, out) {
  284. out.x = Math.max(a.x, b.x);
  285. out.y = Math.max(a.y, b.y);
  286. out.z = Math.max(a.z, b.z);
  287. }
  288. static transformQuat(source, rotation, out) {
  289. 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;
  290. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  291. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  292. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  293. }
  294. static scalarLength(a) {
  295. var x = a.x, y = a.y, z = a.z;
  296. return Math.sqrt(x * x + y * y + z * z);
  297. }
  298. static scalarLengthSquared(a) {
  299. var x = a.x, y = a.y, z = a.z;
  300. return x * x + y * y + z * z;
  301. }
  302. static normalize(s, out) {
  303. var x = s.x, y = s.y, z = s.z;
  304. var len = x * x + y * y + z * z;
  305. if (len > 0) {
  306. len = 1 / Math.sqrt(len);
  307. out.x = x * len;
  308. out.y = y * len;
  309. out.z = z * len;
  310. }
  311. }
  312. static multiply(a, b, out) {
  313. out.x = a.x * b.x;
  314. out.y = a.y * b.y;
  315. out.z = a.z * b.z;
  316. }
  317. static scale(a, b, out) {
  318. out.x = a.x * b;
  319. out.y = a.y * b;
  320. out.z = a.z * b;
  321. }
  322. static lerp(a, b, t, out) {
  323. var ax = a.x, ay = a.y, az = a.z;
  324. out.x = ax + t * (b.x - ax);
  325. out.y = ay + t * (b.y - ay);
  326. out.z = az + t * (b.z - az);
  327. }
  328. static transformV3ToV3(vector, transform, result) {
  329. var intermediate = Vector3._tempVector4;
  330. Vector3.transformV3ToV4(vector, transform, intermediate);
  331. result.x = intermediate.x;
  332. result.y = intermediate.y;
  333. result.z = intermediate.z;
  334. }
  335. static transformV3ToV4(vector, transform, result) {
  336. var vectorX = vector.x;
  337. var vectorY = vector.y;
  338. var vectorZ = vector.z;
  339. var transformElem = transform.elements;
  340. result.x = (vectorX * transformElem[0]) + (vectorY * transformElem[4]) + (vectorZ * transformElem[8]) + transformElem[12];
  341. result.y = (vectorX * transformElem[1]) + (vectorY * transformElem[5]) + (vectorZ * transformElem[9]) + transformElem[13];
  342. result.z = (vectorX * transformElem[2]) + (vectorY * transformElem[6]) + (vectorZ * transformElem[10]) + transformElem[14];
  343. result.w = (vectorX * transformElem[3]) + (vectorY * transformElem[7]) + (vectorZ * transformElem[11]) + transformElem[15];
  344. }
  345. static TransformNormal(normal, transform, result) {
  346. var normalX = normal.x;
  347. var normalY = normal.y;
  348. var normalZ = normal.z;
  349. var transformElem = transform.elements;
  350. result.x = (normalX * transformElem[0]) + (normalY * transformElem[4]) + (normalZ * transformElem[8]);
  351. result.y = (normalX * transformElem[1]) + (normalY * transformElem[5]) + (normalZ * transformElem[9]);
  352. result.z = (normalX * transformElem[2]) + (normalY * transformElem[6]) + (normalZ * transformElem[10]);
  353. }
  354. static transformCoordinate(coordinate, transform, result) {
  355. var coordinateX = coordinate.x;
  356. var coordinateY = coordinate.y;
  357. var coordinateZ = coordinate.z;
  358. var transformElem = transform.elements;
  359. var w = ((coordinateX * transformElem[3]) + (coordinateY * transformElem[7]) + (coordinateZ * transformElem[11]) + transformElem[15]);
  360. result.x = (coordinateX * transformElem[0]) + (coordinateY * transformElem[4]) + (coordinateZ * transformElem[8]) + transformElem[12] / w;
  361. result.y = (coordinateX * transformElem[1]) + (coordinateY * transformElem[5]) + (coordinateZ * transformElem[9]) + transformElem[13] / w;
  362. result.z = (coordinateX * transformElem[2]) + (coordinateY * transformElem[6]) + (coordinateZ * transformElem[10]) + transformElem[14] / w;
  363. }
  364. static Clamp(value, min, max, out) {
  365. var x = value.x;
  366. var y = value.y;
  367. var z = value.z;
  368. var mineX = min.x;
  369. var mineY = min.y;
  370. var mineZ = min.z;
  371. var maxeX = max.x;
  372. var maxeY = max.y;
  373. var maxeZ = max.z;
  374. x = (x > maxeX) ? maxeX : x;
  375. x = (x < mineX) ? mineX : x;
  376. y = (y > maxeY) ? maxeY : y;
  377. y = (y < mineY) ? mineY : y;
  378. z = (z > maxeZ) ? maxeZ : z;
  379. z = (z < mineZ) ? mineZ : z;
  380. out.x = x;
  381. out.y = y;
  382. out.z = z;
  383. }
  384. static add(a, b, out) {
  385. out.x = a.x + b.x;
  386. out.y = a.y + b.y;
  387. out.z = a.z + b.z;
  388. }
  389. static subtract(a, b, o) {
  390. o.x = a.x - b.x;
  391. o.y = a.y - b.y;
  392. o.z = a.z - b.z;
  393. }
  394. static cross(a, b, o) {
  395. var ax = a.x, ay = a.y, az = a.z, bx = b.x, by = b.y, bz = b.z;
  396. o.x = ay * bz - az * by;
  397. o.y = az * bx - ax * bz;
  398. o.z = ax * by - ay * bx;
  399. }
  400. static dot(a, b) {
  401. return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
  402. }
  403. static equals(a, b) {
  404. return MathUtils3D.nearEqual(a.x, b.x) && MathUtils3D.nearEqual(a.y, b.y) && MathUtils3D.nearEqual(a.z, b.z);
  405. }
  406. setValue(x, y, z) {
  407. this.x = x;
  408. this.y = y;
  409. this.z = z;
  410. }
  411. fromArray(array, offset = 0) {
  412. this.x = array[offset + 0];
  413. this.y = array[offset + 1];
  414. this.z = array[offset + 2];
  415. }
  416. cloneTo(destObject) {
  417. var destVector3 = destObject;
  418. destVector3.x = this.x;
  419. destVector3.y = this.y;
  420. destVector3.z = this.z;
  421. }
  422. clone() {
  423. var destVector3 = new Vector3();
  424. this.cloneTo(destVector3);
  425. return destVector3;
  426. }
  427. toDefault() {
  428. this.x = 0;
  429. this.y = 0;
  430. this.z = 0;
  431. }
  432. forNativeElement(nativeElements = null) {
  433. if (nativeElements) {
  434. this.elements = nativeElements;
  435. this.elements[0] = this.x;
  436. this.elements[1] = this.y;
  437. this.elements[2] = this.z;
  438. }
  439. else {
  440. this.elements = new Float32Array([this.x, this.y, this.z]);
  441. }
  442. Vector2.rewriteNumProperty(this, "x", 0);
  443. Vector2.rewriteNumProperty(this, "y", 1);
  444. Vector2.rewriteNumProperty(this, "z", 2);
  445. }
  446. }
  447. Vector3._tempVector4 = new Vector4();
  448. Vector3._ZERO = new Vector3(0.0, 0.0, 0.0);
  449. Vector3._ONE = new Vector3(1.0, 1.0, 1.0);
  450. Vector3._NegativeUnitX = new Vector3(-1, 0, 0);
  451. Vector3._UnitX = new Vector3(1, 0, 0);
  452. Vector3._UnitY = new Vector3(0, 1, 0);
  453. Vector3._UnitZ = new Vector3(0, 0, 1);
  454. Vector3._ForwardRH = new Vector3(0, 0, -1);
  455. Vector3._ForwardLH = new Vector3(0, 0, 1);
  456. Vector3._Up = new Vector3(0, 1, 0);
  457. class Config3D {
  458. constructor() {
  459. this._defaultPhysicsMemory = 16;
  460. this._maxLightCount = 32;
  461. this._lightClusterCount = new Vector3(12, 12, 12);
  462. this._editerEnvironment = false;
  463. this.isAntialias = true;
  464. this.isAlpha = false;
  465. this.premultipliedAlpha = true;
  466. this.isStencil = true;
  467. this.enbaleMultiLight = true;
  468. this.octreeCulling = false;
  469. this.octreeInitialSize = 64.0;
  470. this.octreeInitialCenter = new Vector3(0, 0, 0);
  471. this.octreeMinNodeSize = 2.0;
  472. this.octreeLooseness = 1.25;
  473. this.debugFrustumCulling = false;
  474. this._maxAreaLightCountPerClusterAverage = Math.min(Math.floor(2048 / this._lightClusterCount.z - 1) * 4, this._maxLightCount);
  475. }
  476. get defaultPhysicsMemory() {
  477. return this._defaultPhysicsMemory;
  478. }
  479. set defaultPhysicsMemory(value) {
  480. if (value < 16)
  481. throw "defaultPhysicsMemory must large than 16M";
  482. this._defaultPhysicsMemory = value;
  483. }
  484. get maxLightCount() {
  485. return this._maxLightCount;
  486. }
  487. set maxLightCount(value) {
  488. if (value > 2048) {
  489. this._maxLightCount = 2048;
  490. console.warn("Config3D: maxLightCount must less equal 2048.");
  491. }
  492. else {
  493. this._maxLightCount = value;
  494. }
  495. }
  496. get lightClusterCount() {
  497. return this._lightClusterCount;
  498. }
  499. set lightClusterCount(value) {
  500. if (value.x > 128 || value.y > 128 || value.z > 128) {
  501. this._lightClusterCount.setValue(Math.min(value.x, 128), Math.min(value.y, 128), Math.min(value.z, 128));
  502. console.warn("Config3D: lightClusterCount X and Y、Z must less equal 128.");
  503. }
  504. else {
  505. value.cloneTo(this._lightClusterCount);
  506. }
  507. var maxAreaLightCountWithZ = Math.floor(2048 / this._lightClusterCount.z - 1) * 4;
  508. if (maxAreaLightCountWithZ < this._maxLightCount)
  509. console.warn("Config3D: if the area light(PointLight、SpotLight) count is large than " + maxAreaLightCountWithZ + ",maybe the far away culster will ingonre some light.");
  510. this._maxAreaLightCountPerClusterAverage = Math.min(maxAreaLightCountWithZ, this._maxLightCount);
  511. }
  512. _checkMaxLightCountPerCluster(maxLightCountPerCluster, clusterCountZ) {
  513. return Math.ceil((maxLightCountPerCluster / 4) + 1) * clusterCountZ < 2048;
  514. }
  515. cloneTo(dest) {
  516. var destConfig3D = dest;
  517. destConfig3D._defaultPhysicsMemory = this._defaultPhysicsMemory;
  518. destConfig3D._editerEnvironment = this._editerEnvironment;
  519. destConfig3D.isAntialias = this.isAntialias;
  520. destConfig3D.isAlpha = this.isAlpha;
  521. destConfig3D.premultipliedAlpha = this.premultipliedAlpha;
  522. destConfig3D.isStencil = this.isStencil;
  523. destConfig3D.octreeCulling = this.octreeCulling;
  524. this.octreeInitialCenter.cloneTo(destConfig3D.octreeInitialCenter);
  525. destConfig3D.octreeInitialSize = this.octreeInitialSize;
  526. destConfig3D.octreeMinNodeSize = this.octreeMinNodeSize;
  527. destConfig3D.octreeLooseness = this.octreeLooseness;
  528. destConfig3D.debugFrustumCulling = this.debugFrustumCulling;
  529. destConfig3D.maxLightCount = this.maxLightCount;
  530. destConfig3D.enbaleMultiLight = this.enbaleMultiLight;
  531. var lightClusterCount = destConfig3D.lightClusterCount;
  532. this.lightClusterCount.cloneTo(lightClusterCount);
  533. destConfig3D.lightClusterCount = lightClusterCount;
  534. }
  535. clone() {
  536. var dest = new Config3D();
  537. this.cloneTo(dest);
  538. return dest;
  539. }
  540. }
  541. Config3D._config = new Config3D();
  542. window.Config3D = Config3D;
  543. class ILaya3D {
  544. }
  545. ILaya3D.Scene3D = null;
  546. ILaya3D.MeshRenderStaticBatchManager = null;
  547. ILaya3D.MeshRenderDynamicBatchManager = null;
  548. ILaya3D.SubMeshDynamicBatch = null;
  549. ILaya3D.Laya3D = null;
  550. ILaya3D.Matrix4x4 = null;
  551. class KeyframeNode {
  552. constructor() {
  553. this._ownerPath = [];
  554. this._propertys = [];
  555. this._keyFrames = [];
  556. }
  557. get ownerPathCount() {
  558. return this._ownerPath.length;
  559. }
  560. get propertyCount() {
  561. return this._propertys.length;
  562. }
  563. get keyFramesCount() {
  564. return this._keyFrames.length;
  565. }
  566. _setOwnerPathCount(value) {
  567. this._ownerPath.length = value;
  568. }
  569. _setOwnerPathByIndex(index, value) {
  570. this._ownerPath[index] = value;
  571. }
  572. _joinOwnerPath(sep) {
  573. return this._ownerPath.join(sep);
  574. }
  575. _setPropertyCount(value) {
  576. this._propertys.length = value;
  577. }
  578. _setPropertyByIndex(index, value) {
  579. this._propertys[index] = value;
  580. }
  581. _joinProperty(sep) {
  582. return this._propertys.join(sep);
  583. }
  584. _setKeyframeCount(value) {
  585. this._keyFrames.length = value;
  586. }
  587. _setKeyframeByIndex(index, value) {
  588. this._keyFrames[index] = value;
  589. }
  590. getOwnerPathByIndex(index) {
  591. return this._ownerPath[index];
  592. }
  593. getPropertyByIndex(index) {
  594. return this._propertys[index];
  595. }
  596. getKeyframeByIndex(index) {
  597. return this._keyFrames[index];
  598. }
  599. }
  600. if (window.conch && window.conchKeyframeNode) {
  601. KeyframeNode = window.conchKeyframeNode;
  602. }
  603. if (window.qq && window.qq.webglPlus) {
  604. KeyframeNode = window.qq.webglPlus.conchKeyframeNode;
  605. }
  606. class AnimationEvent {
  607. constructor() {
  608. }
  609. }
  610. class Keyframe {
  611. constructor() {
  612. }
  613. cloneTo(destObject) {
  614. var destKeyFrame = destObject;
  615. destKeyFrame.time = this.time;
  616. }
  617. clone() {
  618. var dest = new Keyframe();
  619. this.cloneTo(dest);
  620. return dest;
  621. }
  622. }
  623. class FloatKeyframe extends Keyframe {
  624. constructor() {
  625. super();
  626. }
  627. cloneTo(destObject) {
  628. super.cloneTo(destObject);
  629. var destKeyFrame = destObject;
  630. destKeyFrame.inTangent = this.inTangent;
  631. destKeyFrame.outTangent = this.outTangent;
  632. destKeyFrame.value = this.value;
  633. }
  634. }
  635. if (window.conch && window.conchFloatKeyframe) {
  636. FloatKeyframe = window.conchFloatKeyframe;
  637. }
  638. if (window.qq && window.qq.webglPlus) {
  639. FloatKeyframe = window.qq.webglPlus.conchFloatKeyframe;
  640. }
  641. class Matrix3x3 {
  642. constructor() {
  643. var e = this.elements = new Float32Array(9);
  644. e[0] = 1;
  645. e[1] = 0;
  646. e[2] = 0;
  647. e[3] = 0;
  648. e[4] = 1;
  649. e[5] = 0;
  650. e[6] = 0;
  651. e[7] = 0;
  652. e[8] = 1;
  653. }
  654. static createRotationQuaternion(rotation, out) {
  655. var rotX = rotation.x;
  656. var rotY = rotation.y;
  657. var rotZ = rotation.z;
  658. var rotW = rotation.w;
  659. var xx = rotX * rotX;
  660. var yy = rotY * rotY;
  661. var zz = rotZ * rotZ;
  662. var xy = rotX * rotY;
  663. var zw = rotZ * rotW;
  664. var zx = rotZ * rotX;
  665. var yw = rotY * rotW;
  666. var yz = rotY * rotZ;
  667. var xw = rotX * rotW;
  668. var resultE = out.elements;
  669. resultE[0] = 1.0 - (2.0 * (yy + zz));
  670. resultE[1] = 2.0 * (xy + zw);
  671. resultE[2] = 2.0 * (zx - yw);
  672. resultE[3] = 2.0 * (xy - zw);
  673. resultE[4] = 1.0 - (2.0 * (zz + xx));
  674. resultE[5] = 2.0 * (yz + xw);
  675. resultE[6] = 2.0 * (zx + yw);
  676. resultE[7] = 2.0 * (yz - xw);
  677. resultE[8] = 1.0 - (2.0 * (yy + xx));
  678. }
  679. static createFromTranslation(trans, out) {
  680. var e = out.elements;
  681. out[0] = 1;
  682. out[1] = 0;
  683. out[2] = 0;
  684. out[3] = 0;
  685. out[4] = 1;
  686. out[5] = 0;
  687. out[6] = trans.x;
  688. out[7] = trans.y;
  689. out[8] = 1;
  690. }
  691. static createFromRotation(rad, out) {
  692. var e = out.elements;
  693. var s = Math.sin(rad), c = Math.cos(rad);
  694. e[0] = c;
  695. e[1] = s;
  696. e[2] = 0;
  697. e[3] = -s;
  698. e[4] = c;
  699. e[5] = 0;
  700. e[6] = 0;
  701. e[7] = 0;
  702. e[8] = 1;
  703. }
  704. static createFromScaling(scale, out) {
  705. var e = out.elements;
  706. e[0] = scale.x;
  707. e[1] = 0;
  708. e[2] = 0;
  709. e[3] = 0;
  710. e[4] = scale.y;
  711. e[5] = 0;
  712. e[6] = 0;
  713. e[7] = 0;
  714. e[8] = scale.z;
  715. }
  716. static createFromMatrix4x4(sou, out) {
  717. var souE = sou.elements;
  718. var outE = out.elements;
  719. outE[0] = souE[0];
  720. outE[1] = souE[1];
  721. outE[2] = souE[2];
  722. outE[3] = souE[4];
  723. outE[4] = souE[5];
  724. outE[5] = souE[6];
  725. outE[6] = souE[8];
  726. outE[7] = souE[9];
  727. outE[8] = souE[10];
  728. }
  729. static multiply(left, right, out) {
  730. var l = left.elements;
  731. var r = right.elements;
  732. var e = out.elements;
  733. var l11 = l[0], l12 = l[1], l13 = l[2];
  734. var l21 = l[3], l22 = l[4], l23 = l[5];
  735. var l31 = l[6], l32 = l[7], l33 = l[8];
  736. var r11 = r[0], r12 = r[1], r13 = r[2];
  737. var r21 = r[3], r22 = r[4], r23 = r[5];
  738. var r31 = r[6], r32 = r[7], r33 = r[8];
  739. e[0] = r11 * l11 + r12 * l21 + r13 * l31;
  740. e[1] = r11 * l12 + r12 * l22 + r13 * r32;
  741. e[2] = r11 * l13 + r12 * l23 + r13 * l33;
  742. e[3] = r21 * l11 + r22 * l21 + r23 * l31;
  743. e[4] = r21 * l12 + r22 * l22 + r23 * l32;
  744. e[5] = r21 * l13 + r22 * l23 + r23 * l33;
  745. e[6] = r31 * l11 + r32 * l21 + r33 * l31;
  746. e[7] = r31 * l12 + r32 * l22 + r33 * l32;
  747. e[8] = r31 * l13 + r32 * l23 + r33 * l33;
  748. }
  749. determinant() {
  750. var f = this.elements;
  751. var a00 = f[0], a01 = f[1], a02 = f[2];
  752. var a10 = f[3], a11 = f[4], a12 = f[5];
  753. var a20 = f[6], a21 = f[7], a22 = f[8];
  754. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  755. }
  756. translate(trans, out) {
  757. var e = out.elements;
  758. var f = this.elements;
  759. var a00 = f[0], a01 = f[1], a02 = f[2];
  760. var a10 = f[3], a11 = f[4], a12 = f[5];
  761. var a20 = f[6], a21 = f[7], a22 = f[8];
  762. var x = trans.x, y = trans.y;
  763. e[0] = a00;
  764. e[1] = a01;
  765. e[2] = a02;
  766. e[3] = a10;
  767. e[4] = a11;
  768. e[5] = a12;
  769. e[6] = x * a00 + y * a10 + a20;
  770. e[7] = x * a01 + y * a11 + a21;
  771. e[8] = x * a02 + y * a12 + a22;
  772. }
  773. rotate(rad, out) {
  774. var e = out.elements;
  775. var f = this.elements;
  776. var a00 = f[0], a01 = f[1], a02 = f[2];
  777. var a10 = f[3], a11 = f[4], a12 = f[5];
  778. var a20 = f[6], a21 = f[7], a22 = f[8];
  779. var s = Math.sin(rad);
  780. var c = Math.cos(rad);
  781. e[0] = c * a00 + s * a10;
  782. e[1] = c * a01 + s * a11;
  783. e[2] = c * a02 + s * a12;
  784. e[3] = c * a10 - s * a00;
  785. e[4] = c * a11 - s * a01;
  786. e[5] = c * a12 - s * a02;
  787. e[6] = a20;
  788. e[7] = a21;
  789. e[8] = a22;
  790. }
  791. scale(scale, out) {
  792. var e = out.elements;
  793. var f = this.elements;
  794. var x = scale.x, y = scale.y;
  795. e[0] = x * f[0];
  796. e[1] = x * f[1];
  797. e[2] = x * f[2];
  798. e[3] = y * f[3];
  799. e[4] = y * f[4];
  800. e[5] = y * f[5];
  801. e[6] = f[6];
  802. e[7] = f[7];
  803. e[8] = f[8];
  804. }
  805. invert(out) {
  806. var e = out.elements;
  807. var f = this.elements;
  808. var a00 = f[0], a01 = f[1], a02 = f[2];
  809. var a10 = f[3], a11 = f[4], a12 = f[5];
  810. var a20 = f[6], a21 = f[7], a22 = f[8];
  811. var b01 = a22 * a11 - a12 * a21;
  812. var b11 = -a22 * a10 + a12 * a20;
  813. var b21 = a21 * a10 - a11 * a20;
  814. var det = a00 * b01 + a01 * b11 + a02 * b21;
  815. if (!det) {
  816. out = null;
  817. }
  818. det = 1.0 / det;
  819. e[0] = b01 * det;
  820. e[1] = (-a22 * a01 + a02 * a21) * det;
  821. e[2] = (a12 * a01 - a02 * a11) * det;
  822. e[3] = b11 * det;
  823. e[4] = (a22 * a00 - a02 * a20) * det;
  824. e[5] = (-a12 * a00 + a02 * a10) * det;
  825. e[6] = b21 * det;
  826. e[7] = (-a21 * a00 + a01 * a20) * det;
  827. e[8] = (a11 * a00 - a01 * a10) * det;
  828. }
  829. transpose(out) {
  830. var e = out.elements;
  831. var f = this.elements;
  832. if (out === this) {
  833. var a01 = f[1], a02 = f[2], a12 = f[5];
  834. e[1] = f[3];
  835. e[2] = f[6];
  836. e[3] = a01;
  837. e[5] = f[7];
  838. e[6] = a02;
  839. e[7] = a12;
  840. }
  841. else {
  842. e[0] = f[0];
  843. e[1] = f[3];
  844. e[2] = f[6];
  845. e[3] = f[1];
  846. e[4] = f[4];
  847. e[5] = f[7];
  848. e[6] = f[2];
  849. e[7] = f[5];
  850. e[8] = f[8];
  851. }
  852. }
  853. identity() {
  854. var e = this.elements;
  855. e[0] = 1;
  856. e[1] = 0;
  857. e[2] = 0;
  858. e[3] = 0;
  859. e[4] = 1;
  860. e[5] = 0;
  861. e[6] = 0;
  862. e[7] = 0;
  863. e[8] = 1;
  864. }
  865. cloneTo(destObject) {
  866. var i, s, d;
  867. s = this.elements;
  868. d = destObject.elements;
  869. if (s === d) {
  870. return;
  871. }
  872. for (i = 0; i < 9; ++i) {
  873. d[i] = s[i];
  874. }
  875. }
  876. clone() {
  877. var dest = new Matrix3x3();
  878. this.cloneTo(dest);
  879. return dest;
  880. }
  881. static lookAt(eye, target, up, out) {
  882. Vector3.subtract(eye, target, Matrix3x3._tempV30);
  883. Vector3.normalize(Matrix3x3._tempV30, Matrix3x3._tempV30);
  884. Vector3.cross(up, Matrix3x3._tempV30, Matrix3x3._tempV31);
  885. Vector3.normalize(Matrix3x3._tempV31, Matrix3x3._tempV31);
  886. Vector3.cross(Matrix3x3._tempV30, Matrix3x3._tempV31, Matrix3x3._tempV32);
  887. var v0 = Matrix3x3._tempV30;
  888. var v1 = Matrix3x3._tempV31;
  889. var v2 = Matrix3x3._tempV32;
  890. var me = out.elements;
  891. me[0] = v1.x;
  892. me[3] = v1.y;
  893. me[6] = v1.z;
  894. me[1] = v2.x;
  895. me[4] = v2.y;
  896. me[7] = v2.z;
  897. me[2] = v0.x;
  898. me[5] = v0.y;
  899. me[8] = v0.z;
  900. }
  901. }
  902. Matrix3x3.DEFAULT = new Matrix3x3();
  903. Matrix3x3._tempV30 = new Vector3();
  904. Matrix3x3._tempV31 = new Vector3();
  905. Matrix3x3._tempV32 = new Vector3();
  906. class Quaternion {
  907. constructor(x = 0, y = 0, z = 0, w = 1, nativeElements = null) {
  908. this.x = x;
  909. this.y = y;
  910. this.z = z;
  911. this.w = w;
  912. }
  913. static createFromYawPitchRoll(yaw, pitch, roll, out) {
  914. var halfRoll = roll * 0.5;
  915. var halfPitch = pitch * 0.5;
  916. var halfYaw = yaw * 0.5;
  917. var sinRoll = Math.sin(halfRoll);
  918. var cosRoll = Math.cos(halfRoll);
  919. var sinPitch = Math.sin(halfPitch);
  920. var cosPitch = Math.cos(halfPitch);
  921. var sinYaw = Math.sin(halfYaw);
  922. var cosYaw = Math.cos(halfYaw);
  923. out.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  924. out.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  925. out.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  926. out.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  927. }
  928. static multiply(left, right, out) {
  929. var lx = left.x;
  930. var ly = left.y;
  931. var lz = left.z;
  932. var lw = left.w;
  933. var rx = right.x;
  934. var ry = right.y;
  935. var rz = right.z;
  936. var rw = right.w;
  937. var a = (ly * rz - lz * ry);
  938. var b = (lz * rx - lx * rz);
  939. var c = (lx * ry - ly * rx);
  940. var d = (lx * rx + ly * ry + lz * rz);
  941. out.x = (lx * rw + rx * lw) + a;
  942. out.y = (ly * rw + ry * lw) + b;
  943. out.z = (lz * rw + rz * lw) + c;
  944. out.w = lw * rw - d;
  945. }
  946. static arcTanAngle(x, y) {
  947. if (x == 0) {
  948. if (y == 1)
  949. return Math.PI / 2;
  950. return -Math.PI / 2;
  951. }
  952. if (x > 0)
  953. return Math.atan(y / x);
  954. if (x < 0) {
  955. if (y > 0)
  956. return Math.atan(y / x) + Math.PI;
  957. return Math.atan(y / x) - Math.PI;
  958. }
  959. return 0;
  960. }
  961. static angleTo(from, location, angle) {
  962. Vector3.subtract(location, from, Quaternion.TEMPVector30);
  963. Vector3.normalize(Quaternion.TEMPVector30, Quaternion.TEMPVector30);
  964. angle.x = Math.asin(Quaternion.TEMPVector30.y);
  965. angle.y = Quaternion.arcTanAngle(-Quaternion.TEMPVector30.z, -Quaternion.TEMPVector30.x);
  966. }
  967. static createFromAxisAngle(axis, rad, out) {
  968. rad = rad * 0.5;
  969. var s = Math.sin(rad);
  970. out.x = s * axis.x;
  971. out.y = s * axis.y;
  972. out.z = s * axis.z;
  973. out.w = Math.cos(rad);
  974. }
  975. static createFromMatrix4x4(mat, out) {
  976. var me = mat.elements;
  977. var sqrt;
  978. var half;
  979. var scale = me[0] + me[5] + me[10];
  980. if (scale > 0.0) {
  981. sqrt = Math.sqrt(scale + 1.0);
  982. out.w = sqrt * 0.5;
  983. sqrt = 0.5 / sqrt;
  984. out.x = (me[6] - me[9]) * sqrt;
  985. out.y = (me[8] - me[2]) * sqrt;
  986. out.z = (me[1] - me[4]) * sqrt;
  987. }
  988. else if ((me[0] >= me[5]) && (me[0] >= me[10])) {
  989. sqrt = Math.sqrt(1.0 + me[0] - me[5] - me[10]);
  990. half = 0.5 / sqrt;
  991. out.x = 0.5 * sqrt;
  992. out.y = (me[1] + me[4]) * half;
  993. out.z = (me[2] + me[8]) * half;
  994. out.w = (me[6] - me[9]) * half;
  995. }
  996. else if (me[5] > me[10]) {
  997. sqrt = Math.sqrt(1.0 + me[5] - me[0] - me[10]);
  998. half = 0.5 / sqrt;
  999. out.x = (me[4] + me[1]) * half;
  1000. out.y = 0.5 * sqrt;
  1001. out.z = (me[9] + me[6]) * half;
  1002. out.w = (me[8] - me[2]) * half;
  1003. }
  1004. else {
  1005. sqrt = Math.sqrt(1.0 + me[10] - me[0] - me[5]);
  1006. half = 0.5 / sqrt;
  1007. out.x = (me[8] + me[2]) * half;
  1008. out.y = (me[9] + me[6]) * half;
  1009. out.z = 0.5 * sqrt;
  1010. out.w = (me[1] - me[4]) * half;
  1011. }
  1012. }
  1013. static slerp(left, right, t, out) {
  1014. 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;
  1015. var omega, cosom, sinom, scale0, scale1;
  1016. cosom = ax * bx + ay * by + az * bz + aw * bw;
  1017. if (cosom < 0.0) {
  1018. cosom = -cosom;
  1019. bx = -bx;
  1020. by = -by;
  1021. bz = -bz;
  1022. bw = -bw;
  1023. }
  1024. if ((1.0 - cosom) > 0.000001) {
  1025. omega = Math.acos(cosom);
  1026. sinom = Math.sin(omega);
  1027. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  1028. scale1 = Math.sin(t * omega) / sinom;
  1029. }
  1030. else {
  1031. scale0 = 1.0 - t;
  1032. scale1 = t;
  1033. }
  1034. out.x = scale0 * ax + scale1 * bx;
  1035. out.y = scale0 * ay + scale1 * by;
  1036. out.z = scale0 * az + scale1 * bz;
  1037. out.w = scale0 * aw + scale1 * bw;
  1038. return out;
  1039. }
  1040. static lerp(left, right, amount, out) {
  1041. var inverse = 1.0 - amount;
  1042. if (Quaternion.dot(left, right) >= 0) {
  1043. out.x = (inverse * left.x) + (amount * right.x);
  1044. out.y = (inverse * left.y) + (amount * right.y);
  1045. out.z = (inverse * left.z) + (amount * right.z);
  1046. out.w = (inverse * left.w) + (amount * right.w);
  1047. }
  1048. else {
  1049. out.x = (inverse * left.x) - (amount * right.x);
  1050. out.y = (inverse * left.y) - (amount * right.y);
  1051. out.z = (inverse * left.z) - (amount * right.z);
  1052. out.w = (inverse * left.w) - (amount * right.w);
  1053. }
  1054. out.normalize(out);
  1055. }
  1056. static add(left, right, out) {
  1057. out.x = left.x + right.x;
  1058. out.y = left.y + right.y;
  1059. out.z = left.z + right.z;
  1060. out.w = left.w + right.w;
  1061. }
  1062. static dot(left, right) {
  1063. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  1064. }
  1065. scaling(scaling, out) {
  1066. out.x = this.x * scaling;
  1067. out.y = this.y * scaling;
  1068. out.z = this.z * scaling;
  1069. out.w = this.w * scaling;
  1070. }
  1071. normalize(out) {
  1072. var len = this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1073. if (len > 0) {
  1074. len = 1 / Math.sqrt(len);
  1075. out.x = this.x * len;
  1076. out.y = this.y * len;
  1077. out.z = this.z * len;
  1078. out.w = this.w * len;
  1079. }
  1080. }
  1081. length() {
  1082. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1083. }
  1084. rotateX(rad, out) {
  1085. rad *= 0.5;
  1086. var bx = Math.sin(rad), bw = Math.cos(rad);
  1087. out.x = this.x * bw + this.w * bx;
  1088. out.y = this.y * bw + this.z * bx;
  1089. out.z = this.z * bw - this.y * bx;
  1090. out.w = this.w * bw - this.x * bx;
  1091. }
  1092. rotateY(rad, out) {
  1093. rad *= 0.5;
  1094. var by = Math.sin(rad), bw = Math.cos(rad);
  1095. out.x = this.x * bw - this.z * by;
  1096. out.y = this.y * bw + this.w * by;
  1097. out.z = this.z * bw + this.x * by;
  1098. out.w = this.w * bw - this.y * by;
  1099. }
  1100. rotateZ(rad, out) {
  1101. rad *= 0.5;
  1102. var bz = Math.sin(rad), bw = Math.cos(rad);
  1103. out.x = this.x * bw + this.y * bz;
  1104. out.y = this.y * bw - this.x * bz;
  1105. out.z = this.z * bw + this.w * bz;
  1106. out.w = this.w * bw - this.z * bz;
  1107. }
  1108. getYawPitchRoll(out) {
  1109. Vector3.transformQuat(Vector3._ForwardRH, this, Quaternion.TEMPVector31);
  1110. Vector3.transformQuat(Vector3._Up, this, Quaternion.TEMPVector32);
  1111. var upe = Quaternion.TEMPVector32;
  1112. Quaternion.angleTo(Vector3._ZERO, Quaternion.TEMPVector31, Quaternion.TEMPVector33);
  1113. var angle = Quaternion.TEMPVector33;
  1114. if (angle.x == Math.PI / 2) {
  1115. angle.y = Quaternion.arcTanAngle(upe.z, upe.x);
  1116. angle.z = 0;
  1117. }
  1118. else if (angle.x == -Math.PI / 2) {
  1119. angle.y = Quaternion.arcTanAngle(-upe.z, -upe.x);
  1120. angle.z = 0;
  1121. }
  1122. else {
  1123. ILaya3D.Matrix4x4.createRotationY(-angle.y, ILaya3D.Matrix4x4.TEMPMatrix0);
  1124. ILaya3D.Matrix4x4.createRotationX(-angle.x, ILaya3D.Matrix4x4.TEMPMatrix1);
  1125. Vector3.transformCoordinate(Quaternion.TEMPVector32, ILaya3D.Matrix4x4.TEMPMatrix0, Quaternion.TEMPVector32);
  1126. Vector3.transformCoordinate(Quaternion.TEMPVector32, ILaya3D.Matrix4x4.TEMPMatrix1, Quaternion.TEMPVector32);
  1127. angle.z = Quaternion.arcTanAngle(upe.y, -upe.x);
  1128. }
  1129. if (angle.y <= -Math.PI)
  1130. angle.y = Math.PI;
  1131. if (angle.z <= -Math.PI)
  1132. angle.z = Math.PI;
  1133. if (angle.y >= Math.PI && angle.z >= Math.PI) {
  1134. angle.y = 0;
  1135. angle.z = 0;
  1136. angle.x = Math.PI - angle.x;
  1137. }
  1138. var oe = out;
  1139. oe.x = angle.y;
  1140. oe.y = angle.x;
  1141. oe.z = angle.z;
  1142. }
  1143. invert(out) {
  1144. var a0 = this.x, a1 = this.y, a2 = this.z, a3 = this.w;
  1145. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  1146. var invDot = dot ? 1.0 / dot : 0;
  1147. out.x = -a0 * invDot;
  1148. out.y = -a1 * invDot;
  1149. out.z = -a2 * invDot;
  1150. out.w = a3 * invDot;
  1151. }
  1152. identity() {
  1153. this.x = 0;
  1154. this.y = 0;
  1155. this.z = 0;
  1156. this.w = 1;
  1157. }
  1158. fromArray(array, offset = 0) {
  1159. this.x = array[offset + 0];
  1160. this.y = array[offset + 1];
  1161. this.z = array[offset + 2];
  1162. this.w = array[offset + 3];
  1163. }
  1164. cloneTo(destObject) {
  1165. if (this === destObject) {
  1166. return;
  1167. }
  1168. destObject.x = this.x;
  1169. destObject.y = this.y;
  1170. destObject.z = this.z;
  1171. destObject.w = this.w;
  1172. }
  1173. clone() {
  1174. var dest = new Quaternion();
  1175. this.cloneTo(dest);
  1176. return dest;
  1177. }
  1178. equals(b) {
  1179. 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);
  1180. }
  1181. static rotationLookAt(forward, up, out) {
  1182. Quaternion.lookAt(Vector3._ZERO, forward, up, out);
  1183. }
  1184. static lookAt(eye, target, up, out) {
  1185. Matrix3x3.lookAt(eye, target, up, Quaternion._tempMatrix3x3);
  1186. Quaternion.rotationMatrix(Quaternion._tempMatrix3x3, out);
  1187. }
  1188. lengthSquared() {
  1189. return (this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w);
  1190. }
  1191. static invert(value, out) {
  1192. var lengthSq = value.lengthSquared();
  1193. if (!MathUtils3D.isZero(lengthSq)) {
  1194. lengthSq = 1.0 / lengthSq;
  1195. out.x = -value.x * lengthSq;
  1196. out.y = -value.y * lengthSq;
  1197. out.z = -value.z * lengthSq;
  1198. out.w = value.w * lengthSq;
  1199. }
  1200. }
  1201. static rotationMatrix(matrix3x3, out) {
  1202. var me = matrix3x3.elements;
  1203. var m11 = me[0];
  1204. var m12 = me[1];
  1205. var m13 = me[2];
  1206. var m21 = me[3];
  1207. var m22 = me[4];
  1208. var m23 = me[5];
  1209. var m31 = me[6];
  1210. var m32 = me[7];
  1211. var m33 = me[8];
  1212. var sqrt, half;
  1213. var scale = m11 + m22 + m33;
  1214. if (scale > 0) {
  1215. sqrt = Math.sqrt(scale + 1);
  1216. out.w = sqrt * 0.5;
  1217. sqrt = 0.5 / sqrt;
  1218. out.x = (m23 - m32) * sqrt;
  1219. out.y = (m31 - m13) * sqrt;
  1220. out.z = (m12 - m21) * sqrt;
  1221. }
  1222. else if ((m11 >= m22) && (m11 >= m33)) {
  1223. sqrt = Math.sqrt(1 + m11 - m22 - m33);
  1224. half = 0.5 / sqrt;
  1225. out.x = 0.5 * sqrt;
  1226. out.y = (m12 + m21) * half;
  1227. out.z = (m13 + m31) * half;
  1228. out.w = (m23 - m32) * half;
  1229. }
  1230. else if (m22 > m33) {
  1231. sqrt = Math.sqrt(1 + m22 - m11 - m33);
  1232. half = 0.5 / sqrt;
  1233. out.x = (m21 + m12) * half;
  1234. out.y = 0.5 * sqrt;
  1235. out.z = (m32 + m23) * half;
  1236. out.w = (m31 - m13) * half;
  1237. }
  1238. else {
  1239. sqrt = Math.sqrt(1 + m33 - m11 - m22);
  1240. half = 0.5 / sqrt;
  1241. out.x = (m31 + m13) * half;
  1242. out.y = (m32 + m23) * half;
  1243. out.z = 0.5 * sqrt;
  1244. out.w = (m12 - m21) * half;
  1245. }
  1246. }
  1247. forNativeElement(nativeElements = null) {
  1248. if (nativeElements) {
  1249. this.elements = nativeElements;
  1250. this.elements[0] = this.x;
  1251. this.elements[1] = this.y;
  1252. this.elements[2] = this.z;
  1253. this.elements[3] = this.w;
  1254. }
  1255. else {
  1256. this.elements = new Float32Array([this.x, this.y, this.z, this.w]);
  1257. }
  1258. Vector2.rewriteNumProperty(this, "x", 0);
  1259. Vector2.rewriteNumProperty(this, "y", 1);
  1260. Vector2.rewriteNumProperty(this, "z", 2);
  1261. Vector2.rewriteNumProperty(this, "w", 3);
  1262. }
  1263. }
  1264. Quaternion.TEMPVector30 = new Vector3();
  1265. Quaternion.TEMPVector31 = new Vector3();
  1266. Quaternion.TEMPVector32 = new Vector3();
  1267. Quaternion.TEMPVector33 = new Vector3();
  1268. Quaternion._tempMatrix3x3 = new Matrix3x3();
  1269. Quaternion.DEFAULT = new Quaternion();
  1270. Quaternion.NAN = new Quaternion(NaN, NaN, NaN, NaN);
  1271. class QuaternionKeyframe extends Keyframe {
  1272. constructor() {
  1273. super();
  1274. this.inTangent = new Vector4();
  1275. this.outTangent = new Vector4();
  1276. this.value = new Quaternion();
  1277. }
  1278. cloneTo(dest) {
  1279. super.cloneTo(dest);
  1280. var destKeyFarme = dest;
  1281. this.inTangent.cloneTo(destKeyFarme.inTangent);
  1282. this.outTangent.cloneTo(destKeyFarme.outTangent);
  1283. this.value.cloneTo(destKeyFarme.value);
  1284. }
  1285. }
  1286. if (window.conch && window.conchFloatArrayKeyframe) {
  1287. QuaternionKeyframe = window.conchFloatArrayKeyframe;
  1288. }
  1289. if (window.qq && window.qq.webglPlus) {
  1290. QuaternionKeyframe = window.qq.webglPlus.conchFloatArrayKeyframe;
  1291. }
  1292. class Vector3Keyframe extends Keyframe {
  1293. constructor() {
  1294. super();
  1295. this.inTangent = new Vector3();
  1296. this.outTangent = new Vector3();
  1297. this.value = new Vector3();
  1298. }
  1299. cloneTo(dest) {
  1300. super.cloneTo(dest);
  1301. var destKeyFarme = dest;
  1302. this.inTangent.cloneTo(destKeyFarme.inTangent);
  1303. this.outTangent.cloneTo(destKeyFarme.outTangent);
  1304. this.value.cloneTo(destKeyFarme.value);
  1305. }
  1306. }
  1307. if (window.conch && window.conchFloatArrayKeyframe) {
  1308. Vector3Keyframe = window.conchFloatArrayKeyframe;
  1309. }
  1310. if (window.qq && window.qq.webglPlus) {
  1311. Vector3Keyframe = window.qq.webglPlus.conchFloatArrayKeyframe;
  1312. }
  1313. class ConchVector4 {
  1314. constructor(x = 0, y = 0, z = 0, w = 0) {
  1315. var v = this.elements = new Float32Array(4);
  1316. v[0] = x;
  1317. v[1] = y;
  1318. v[2] = z;
  1319. v[3] = w;
  1320. }
  1321. get x() {
  1322. return this.elements[0];
  1323. }
  1324. set x(value) {
  1325. this.elements[0] = value;
  1326. }
  1327. get y() {
  1328. return this.elements[1];
  1329. }
  1330. set y(value) {
  1331. this.elements[1] = value;
  1332. }
  1333. get z() {
  1334. return this.elements[2];
  1335. }
  1336. set z(value) {
  1337. this.elements[2] = value;
  1338. }
  1339. get w() {
  1340. return this.elements[3];
  1341. }
  1342. set w(value) {
  1343. this.elements[3] = value;
  1344. }
  1345. fromArray(array, offset = 0) {
  1346. this.elements[0] = array[offset + 0];
  1347. this.elements[1] = array[offset + 1];
  1348. this.elements[2] = array[offset + 2];
  1349. this.elements[3] = array[offset + 3];
  1350. }
  1351. cloneTo(destObject) {
  1352. var destVector4 = destObject;
  1353. var destE = destVector4.elements;
  1354. var s = this.elements;
  1355. destE[0] = s[0];
  1356. destE[1] = s[1];
  1357. destE[2] = s[2];
  1358. destE[3] = s[3];
  1359. }
  1360. clone() {
  1361. var destVector4 = new ConchVector4();
  1362. this.cloneTo(destVector4);
  1363. return destVector4;
  1364. }
  1365. static lerp(a, b, t, out) {
  1366. var e = out.elements;
  1367. var f = a.elements;
  1368. var g = b.elements;
  1369. var ax = f[0], ay = f[1], az = f[2], aw = f[3];
  1370. e[0] = ax + t * (g[0] - ax);
  1371. e[1] = ay + t * (g[1] - ay);
  1372. e[2] = az + t * (g[2] - az);
  1373. e[3] = aw + t * (g[3] - aw);
  1374. }
  1375. static transformByM4x4(vector4, m4x4, out) {
  1376. var ve = vector4.elements;
  1377. var vx = ve[0];
  1378. var vy = ve[1];
  1379. var vz = ve[2];
  1380. var vw = ve[3];
  1381. var me = m4x4.elements;
  1382. var oe = out.elements;
  1383. oe[0] = vx * me[0] + vy * me[4] + vz * me[8] + vw * me[12];
  1384. oe[1] = vx * me[1] + vy * me[5] + vz * me[9] + vw * me[13];
  1385. oe[2] = vx * me[2] + vy * me[6] + vz * me[10] + vw * me[14];
  1386. oe[3] = vx * me[3] + vy * me[7] + vz * me[11] + vw * me[15];
  1387. }
  1388. static equals(a, b) {
  1389. var ae = a.elements;
  1390. var be = b.elements;
  1391. 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]));
  1392. }
  1393. length() {
  1394. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1395. }
  1396. lengthSquared() {
  1397. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1398. }
  1399. static normalize(s, out) {
  1400. var se = s.elements;
  1401. var oe = out.elements;
  1402. var len = s.length();
  1403. if (len > 0) {
  1404. oe[0] = se[0] * len;
  1405. oe[1] = se[1] * len;
  1406. oe[2] = se[2] * len;
  1407. oe[3] = se[3] * len;
  1408. }
  1409. }
  1410. static add(a, b, out) {
  1411. var oe = out.elements;
  1412. var ae = a.elements;
  1413. var be = b.elements;
  1414. oe[0] = ae[0] + be[0];
  1415. oe[1] = ae[1] + be[1];
  1416. oe[2] = ae[2] + be[2];
  1417. oe[3] = ae[3] + be[3];
  1418. }
  1419. static subtract(a, b, out) {
  1420. var oe = out.elements;
  1421. var ae = a.elements;
  1422. var be = b.elements;
  1423. oe[0] = ae[0] - be[0];
  1424. oe[1] = ae[1] - be[1];
  1425. oe[2] = ae[2] - be[2];
  1426. oe[3] = ae[3] - be[3];
  1427. }
  1428. static multiply(a, b, out) {
  1429. var oe = out.elements;
  1430. var ae = a.elements;
  1431. var be = b.elements;
  1432. oe[0] = ae[0] * be[0];
  1433. oe[1] = ae[1] * be[1];
  1434. oe[2] = ae[2] * be[2];
  1435. oe[3] = ae[3] * be[3];
  1436. }
  1437. static scale(a, b, out) {
  1438. var oe = out.elements;
  1439. var ae = a.elements;
  1440. oe[0] = ae[0] * b;
  1441. oe[1] = ae[1] * b;
  1442. oe[2] = ae[2] * b;
  1443. oe[3] = ae[3] * b;
  1444. }
  1445. static Clamp(value, min, max, out) {
  1446. var valuee = value.elements;
  1447. var x = valuee[0];
  1448. var y = valuee[1];
  1449. var z = valuee[2];
  1450. var w = valuee[3];
  1451. var mine = min.elements;
  1452. var mineX = mine[0];
  1453. var mineY = mine[1];
  1454. var mineZ = mine[2];
  1455. var mineW = mine[3];
  1456. var maxe = max.elements;
  1457. var maxeX = maxe[0];
  1458. var maxeY = maxe[1];
  1459. var maxeZ = maxe[2];
  1460. var maxeW = maxe[3];
  1461. var oute = out.elements;
  1462. x = (x > maxeX) ? maxeX : x;
  1463. x = (x < mineX) ? mineX : x;
  1464. y = (y > maxeY) ? maxeY : y;
  1465. y = (y < mineY) ? mineY : y;
  1466. z = (z > maxeZ) ? maxeZ : z;
  1467. z = (z < mineZ) ? mineZ : z;
  1468. w = (w > maxeW) ? maxeW : w;
  1469. w = (w < mineW) ? mineW : w;
  1470. oute[0] = x;
  1471. oute[1] = y;
  1472. oute[2] = z;
  1473. oute[3] = w;
  1474. }
  1475. static distanceSquared(value1, value2) {
  1476. var value1e = value1.elements;
  1477. var value2e = value2.elements;
  1478. var x = value1e[0] - value2e[0];
  1479. var y = value1e[1] - value2e[1];
  1480. var z = value1e[2] - value2e[2];
  1481. var w = value1e[3] - value2e[3];
  1482. return (x * x) + (y * y) + (z * z) + (w * w);
  1483. }
  1484. static distance(value1, value2) {
  1485. var value1e = value1.elements;
  1486. var value2e = value2.elements;
  1487. var x = value1e[0] - value2e[0];
  1488. var y = value1e[1] - value2e[1];
  1489. var z = value1e[2] - value2e[2];
  1490. var w = value1e[3] - value2e[3];
  1491. return Math.sqrt((x * x) + (y * y) + (z * z) + (w * w));
  1492. }
  1493. static dot(a, b) {
  1494. var ae = a.elements;
  1495. var be = b.elements;
  1496. var r = (ae[0] * be[0]) + (ae[1] * be[1]) + (ae[2] * be[2]) + (ae[3] * be[3]);
  1497. return r;
  1498. }
  1499. static min(a, b, out) {
  1500. var e = out.elements;
  1501. var f = a.elements;
  1502. var g = b.elements;
  1503. e[0] = Math.min(f[0], g[0]);
  1504. e[1] = Math.min(f[1], g[1]);
  1505. e[2] = Math.min(f[2], g[2]);
  1506. e[3] = Math.min(f[3], g[3]);
  1507. }
  1508. static max(a, b, out) {
  1509. var e = out.elements;
  1510. var f = a.elements;
  1511. var g = b.elements;
  1512. e[0] = Math.max(f[0], g[0]);
  1513. e[1] = Math.max(f[1], g[1]);
  1514. e[2] = Math.max(f[2], g[2]);
  1515. e[3] = Math.max(f[3], g[3]);
  1516. }
  1517. }
  1518. ConchVector4.ZERO = new ConchVector4();
  1519. ConchVector4.ONE = new ConchVector4(1.0, 1.0, 1.0, 1.0);
  1520. ConchVector4.UnitX = new ConchVector4(1.0, 0.0, 0.0, 0.0);
  1521. ConchVector4.UnitY = new ConchVector4(0.0, 1.0, 0.0, 0.0);
  1522. ConchVector4.UnitZ = new ConchVector4(0.0, 0.0, 1.0, 0.0);
  1523. ConchVector4.UnitW = new ConchVector4(0.0, 0.0, 0.0, 1.0);
  1524. class ConchVector3 {
  1525. constructor(x = 0, y = 0, z = 0, nativeElements = null) {
  1526. var v;
  1527. if (nativeElements) {
  1528. v = nativeElements;
  1529. }
  1530. else {
  1531. v = new Float32Array(3);
  1532. }
  1533. this.elements = v;
  1534. v[0] = x;
  1535. v[1] = y;
  1536. v[2] = z;
  1537. }
  1538. static distanceSquared(value1, value2) {
  1539. var value1e = value1.elements;
  1540. var value2e = value2.elements;
  1541. var x = value1e[0] - value2e[0];
  1542. var y = value1e[1] - value2e[1];
  1543. var z = value1e[2] - value2e[2];
  1544. return (x * x) + (y * y) + (z * z);
  1545. }
  1546. static distance(value1, value2) {
  1547. var value1e = value1.elements;
  1548. var value2e = value2.elements;
  1549. var x = value1e[0] - value2e[0];
  1550. var y = value1e[1] - value2e[1];
  1551. var z = value1e[2] - value2e[2];
  1552. return Math.sqrt((x * x) + (y * y) + (z * z));
  1553. }
  1554. static min(a, b, out) {
  1555. var e = out.elements;
  1556. var f = a.elements;
  1557. var g = b.elements;
  1558. e[0] = Math.min(f[0], g[0]);
  1559. e[1] = Math.min(f[1], g[1]);
  1560. e[2] = Math.min(f[2], g[2]);
  1561. }
  1562. static max(a, b, out) {
  1563. var e = out.elements;
  1564. var f = a.elements;
  1565. var g = b.elements;
  1566. e[0] = Math.max(f[0], g[0]);
  1567. e[1] = Math.max(f[1], g[1]);
  1568. e[2] = Math.max(f[2], g[2]);
  1569. }
  1570. static transformQuat(source, rotation, out) {
  1571. var destination = out.elements;
  1572. var se = source.elements;
  1573. var re = rotation.elements;
  1574. 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;
  1575. destination[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1576. destination[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1577. destination[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1578. }
  1579. static scalarLength(a) {
  1580. var f = a.elements;
  1581. var x = f[0], y = f[1], z = f[2];
  1582. return Math.sqrt(x * x + y * y + z * z);
  1583. }
  1584. static scalarLengthSquared(a) {
  1585. var f = a.elements;
  1586. var x = f[0], y = f[1], z = f[2];
  1587. return x * x + y * y + z * z;
  1588. }
  1589. static normalize(s, out) {
  1590. var se = s.elements;
  1591. var oe = out.elements;
  1592. var x = se[0], y = se[1], z = se[2];
  1593. var len = x * x + y * y + z * z;
  1594. if (len > 0) {
  1595. len = 1 / Math.sqrt(len);
  1596. oe[0] = se[0] * len;
  1597. oe[1] = se[1] * len;
  1598. oe[2] = se[2] * len;
  1599. }
  1600. }
  1601. static multiply(a, b, out) {
  1602. var e = out.elements;
  1603. var f = a.elements;
  1604. var g = b.elements;
  1605. e[0] = f[0] * g[0];
  1606. e[1] = f[1] * g[1];
  1607. e[2] = f[2] * g[2];
  1608. }
  1609. static scale(a, b, out) {
  1610. var e = out.elements;
  1611. var f = a.elements;
  1612. e[0] = f[0] * b;
  1613. e[1] = f[1] * b;
  1614. e[2] = f[2] * b;
  1615. }
  1616. static lerp(a, b, t, out) {
  1617. var e = out.elements;
  1618. var f = a.elements;
  1619. var g = b.elements;
  1620. var ax = f[0], ay = f[1], az = f[2];
  1621. e[0] = ax + t * (g[0] - ax);
  1622. e[1] = ay + t * (g[1] - ay);
  1623. e[2] = az + t * (g[2] - az);
  1624. }
  1625. static transformV3ToV3(vector, transform, result) {
  1626. var intermediate = ConchVector3._tempVector4;
  1627. ConchVector3.transformV3ToV4(vector, transform, intermediate);
  1628. var intermediateElem = intermediate.elements;
  1629. var resultElem = result.elements;
  1630. resultElem[0] = intermediateElem[0];
  1631. resultElem[1] = intermediateElem[1];
  1632. resultElem[2] = intermediateElem[2];
  1633. }
  1634. static transformV3ToV4(vector, transform, result) {
  1635. var vectorElem = vector.elements;
  1636. var vectorX = vectorElem[0];
  1637. var vectorY = vectorElem[1];
  1638. var vectorZ = vectorElem[2];
  1639. var transformElem = transform.elements;
  1640. var resultElem = result.elements;
  1641. resultElem[0] = (vectorX * transformElem[0]) + (vectorY * transformElem[4]) + (vectorZ * transformElem[8]) + transformElem[12];
  1642. resultElem[1] = (vectorX * transformElem[1]) + (vectorY * transformElem[5]) + (vectorZ * transformElem[9]) + transformElem[13];
  1643. resultElem[2] = (vectorX * transformElem[2]) + (vectorY * transformElem[6]) + (vectorZ * transformElem[10]) + transformElem[14];
  1644. resultElem[3] = (vectorX * transformElem[3]) + (vectorY * transformElem[7]) + (vectorZ * transformElem[11]) + transformElem[15];
  1645. }
  1646. static TransformNormal(normal, transform, result) {
  1647. var normalElem = normal.elements;
  1648. var normalX = normalElem[0];
  1649. var normalY = normalElem[1];
  1650. var normalZ = normalElem[2];
  1651. var transformElem = transform.elements;
  1652. var resultElem = result.elements;
  1653. resultElem[0] = (normalX * transformElem[0]) + (normalY * transformElem[4]) + (normalZ * transformElem[8]);
  1654. resultElem[1] = (normalX * transformElem[1]) + (normalY * transformElem[5]) + (normalZ * transformElem[9]);
  1655. resultElem[2] = (normalX * transformElem[2]) + (normalY * transformElem[6]) + (normalZ * transformElem[10]);
  1656. }
  1657. static transformCoordinate(coordinate, transform, result) {
  1658. var coordinateElem = coordinate.elements;
  1659. var coordinateX = coordinateElem[0];
  1660. var coordinateY = coordinateElem[1];
  1661. var coordinateZ = coordinateElem[2];
  1662. var transformElem = transform.elements;
  1663. var w = ((coordinateX * transformElem[3]) + (coordinateY * transformElem[7]) + (coordinateZ * transformElem[11]) + transformElem[15]);
  1664. var resultElem = result.elements;
  1665. resultElem[0] = (coordinateX * transformElem[0]) + (coordinateY * transformElem[4]) + (coordinateZ * transformElem[8]) + transformElem[12] / w;
  1666. resultElem[1] = (coordinateX * transformElem[1]) + (coordinateY * transformElem[5]) + (coordinateZ * transformElem[9]) + transformElem[13] / w;
  1667. resultElem[2] = (coordinateX * transformElem[2]) + (coordinateY * transformElem[6]) + (coordinateZ * transformElem[10]) + transformElem[14] / w;
  1668. }
  1669. static Clamp(value, min, max, out) {
  1670. var valuee = value.elements;
  1671. var x = valuee[0];
  1672. var y = valuee[1];
  1673. var z = valuee[2];
  1674. var mine = min.elements;
  1675. var mineX = mine[0];
  1676. var mineY = mine[1];
  1677. var mineZ = mine[2];
  1678. var maxe = max.elements;
  1679. var maxeX = maxe[0];
  1680. var maxeY = maxe[1];
  1681. var maxeZ = maxe[2];
  1682. var oute = out.elements;
  1683. x = (x > maxeX) ? maxeX : x;
  1684. x = (x < mineX) ? mineX : x;
  1685. y = (y > maxeY) ? maxeY : y;
  1686. y = (y < mineY) ? mineY : y;
  1687. z = (z > maxeZ) ? maxeZ : z;
  1688. z = (z < mineZ) ? mineZ : z;
  1689. oute[0] = x;
  1690. oute[1] = y;
  1691. oute[2] = z;
  1692. }
  1693. static add(a, b, out) {
  1694. var e = out.elements;
  1695. var f = a.elements;
  1696. var g = b.elements;
  1697. e[0] = f[0] + g[0];
  1698. e[1] = f[1] + g[1];
  1699. e[2] = f[2] + g[2];
  1700. }
  1701. static subtract(a, b, o) {
  1702. var oe = o.elements;
  1703. var ae = a.elements;
  1704. var be = b.elements;
  1705. oe[0] = ae[0] - be[0];
  1706. oe[1] = ae[1] - be[1];
  1707. oe[2] = ae[2] - be[2];
  1708. }
  1709. static cross(a, b, o) {
  1710. var ae = a.elements;
  1711. var be = b.elements;
  1712. var oe = o.elements;
  1713. var ax = ae[0], ay = ae[1], az = ae[2], bx = be[0], by = be[1], bz = be[2];
  1714. oe[0] = ay * bz - az * by;
  1715. oe[1] = az * bx - ax * bz;
  1716. oe[2] = ax * by - ay * bx;
  1717. }
  1718. static dot(a, b) {
  1719. var ae = a.elements;
  1720. var be = b.elements;
  1721. var r = (ae[0] * be[0]) + (ae[1] * be[1]) + (ae[2] * be[2]);
  1722. return r;
  1723. }
  1724. static equals(a, b) {
  1725. var ae = a.elements;
  1726. var be = b.elements;
  1727. return MathUtils3D.nearEqual(ae[0], be[0]) && MathUtils3D.nearEqual(ae[1], be[1]) && MathUtils3D.nearEqual(ae[2], be[2]);
  1728. }
  1729. get x() {
  1730. return this.elements[0];
  1731. }
  1732. set x(value) {
  1733. this.elements[0] = value;
  1734. }
  1735. get y() {
  1736. return this.elements[1];
  1737. }
  1738. set y(value) {
  1739. this.elements[1] = value;
  1740. }
  1741. get z() {
  1742. return this.elements[2];
  1743. }
  1744. set z(value) {
  1745. this.elements[2] = value;
  1746. }
  1747. setValue(x, y, z) {
  1748. this.elements[0] = x;
  1749. this.elements[1] = y;
  1750. this.elements[2] = z;
  1751. }
  1752. fromArray(array, offset = 0) {
  1753. this.elements[0] = array[offset + 0];
  1754. this.elements[1] = array[offset + 1];
  1755. this.elements[2] = array[offset + 2];
  1756. }
  1757. cloneTo(destObject) {
  1758. var destVector3 = destObject;
  1759. var destE = destVector3.elements;
  1760. var s = this.elements;
  1761. destE[0] = s[0];
  1762. destE[1] = s[1];
  1763. destE[2] = s[2];
  1764. }
  1765. clone() {
  1766. var destVector3 = new ConchVector3();
  1767. this.cloneTo(destVector3);
  1768. return destVector3;
  1769. }
  1770. toDefault() {
  1771. this.elements[0] = 0;
  1772. this.elements[1] = 0;
  1773. this.elements[2] = 0;
  1774. }
  1775. }
  1776. ConchVector3._tempVector4 = new ConchVector4();
  1777. ConchVector3.ZERO = new ConchVector3(0.0, 0.0, 0.0);
  1778. ConchVector3.ONE = new ConchVector3(1.0, 1.0, 1.0);
  1779. ConchVector3.NegativeUnitX = new ConchVector3(-1, 0, 0);
  1780. ConchVector3.UnitX = new ConchVector3(1, 0, 0);
  1781. ConchVector3.UnitY = new ConchVector3(0, 1, 0);
  1782. ConchVector3.UnitZ = new ConchVector3(0, 0, 1);
  1783. ConchVector3.ForwardRH = new ConchVector3(0, 0, -1);
  1784. ConchVector3.ForwardLH = new ConchVector3(0, 0, 1);
  1785. ConchVector3.Up = new ConchVector3(0, 1, 0);
  1786. ConchVector3.NAN = new ConchVector3(NaN, NaN, NaN);
  1787. class Matrix4x4 {
  1788. 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) {
  1789. var e = elements ? this.elements = elements : this.elements = new Float32Array(16);
  1790. e[0] = m11;
  1791. e[1] = m12;
  1792. e[2] = m13;
  1793. e[3] = m14;
  1794. e[4] = m21;
  1795. e[5] = m22;
  1796. e[6] = m23;
  1797. e[7] = m24;
  1798. e[8] = m31;
  1799. e[9] = m32;
  1800. e[10] = m33;
  1801. e[11] = m34;
  1802. e[12] = m41;
  1803. e[13] = m42;
  1804. e[14] = m43;
  1805. e[15] = m44;
  1806. }
  1807. static createRotationX(rad, out) {
  1808. var oe = out.elements;
  1809. var s = Math.sin(rad), c = Math.cos(rad);
  1810. oe[1] = oe[2] = oe[3] = oe[4] = oe[7] = oe[8] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  1811. oe[0] = oe[15] = 1;
  1812. oe[5] = oe[10] = c;
  1813. oe[6] = s;
  1814. oe[9] = -s;
  1815. }
  1816. static createRotationY(rad, out) {
  1817. var oe = out.elements;
  1818. var s = Math.sin(rad), c = Math.cos(rad);
  1819. oe[1] = oe[3] = oe[4] = oe[6] = oe[7] = oe[9] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  1820. oe[5] = oe[15] = 1;
  1821. oe[0] = oe[10] = c;
  1822. oe[2] = -s;
  1823. oe[8] = s;
  1824. }
  1825. static createRotationZ(rad, out) {
  1826. var oe = out.elements;
  1827. var s = Math.sin(rad), c = Math.cos(rad);
  1828. oe[2] = oe[3] = oe[6] = oe[7] = oe[8] = oe[9] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  1829. oe[10] = oe[15] = 1;
  1830. oe[0] = oe[5] = c;
  1831. oe[1] = s;
  1832. oe[4] = -s;
  1833. }
  1834. static createRotationYawPitchRoll(yaw, pitch, roll, result) {
  1835. Quaternion.createFromYawPitchRoll(yaw, pitch, roll, Matrix4x4._tempQuaternion);
  1836. Matrix4x4.createRotationQuaternion(Matrix4x4._tempQuaternion, result);
  1837. }
  1838. static createRotationAxis(axis, angle, result) {
  1839. var x = axis.x;
  1840. var y = axis.y;
  1841. var z = axis.z;
  1842. var cos = Math.cos(angle);
  1843. var sin = Math.sin(angle);
  1844. var xx = x * x;
  1845. var yy = y * y;
  1846. var zz = z * z;
  1847. var xy = x * y;
  1848. var xz = x * z;
  1849. var yz = y * z;
  1850. var resultE = result.elements;
  1851. resultE[3] = resultE[7] = resultE[11] = resultE[12] = resultE[13] = resultE[14] = 0;
  1852. resultE[15] = 1.0;
  1853. resultE[0] = xx + (cos * (1.0 - xx));
  1854. resultE[1] = (xy - (cos * xy)) + (sin * z);
  1855. resultE[2] = (xz - (cos * xz)) - (sin * y);
  1856. resultE[4] = (xy - (cos * xy)) - (sin * z);
  1857. resultE[5] = yy + (cos * (1.0 - yy));
  1858. resultE[6] = (yz - (cos * yz)) + (sin * x);
  1859. resultE[8] = (xz - (cos * xz)) + (sin * y);
  1860. resultE[9] = (yz - (cos * yz)) - (sin * x);
  1861. resultE[10] = zz + (cos * (1.0 - zz));
  1862. }
  1863. setRotation(rotation) {
  1864. var rotationX = rotation.x;
  1865. var rotationY = rotation.y;
  1866. var rotationZ = rotation.z;
  1867. var rotationW = rotation.w;
  1868. var xx = rotationX * rotationX;
  1869. var yy = rotationY * rotationY;
  1870. var zz = rotationZ * rotationZ;
  1871. var xy = rotationX * rotationY;
  1872. var zw = rotationZ * rotationW;
  1873. var zx = rotationZ * rotationX;
  1874. var yw = rotationY * rotationW;
  1875. var yz = rotationY * rotationZ;
  1876. var xw = rotationX * rotationW;
  1877. var e = this.elements;
  1878. e[0] = 1.0 - (2.0 * (yy + zz));
  1879. e[1] = 2.0 * (xy + zw);
  1880. e[2] = 2.0 * (zx - yw);
  1881. e[4] = 2.0 * (xy - zw);
  1882. e[5] = 1.0 - (2.0 * (zz + xx));
  1883. e[6] = 2.0 * (yz + xw);
  1884. e[8] = 2.0 * (zx + yw);
  1885. e[9] = 2.0 * (yz - xw);
  1886. e[10] = 1.0 - (2.0 * (yy + xx));
  1887. }
  1888. setPosition(position) {
  1889. var e = this.elements;
  1890. e[12] = position.x;
  1891. e[13] = position.y;
  1892. e[14] = position.z;
  1893. }
  1894. static createRotationQuaternion(rotation, result) {
  1895. var resultE = result.elements;
  1896. var rotationX = rotation.x;
  1897. var rotationY = rotation.y;
  1898. var rotationZ = rotation.z;
  1899. var rotationW = rotation.w;
  1900. var xx = rotationX * rotationX;
  1901. var yy = rotationY * rotationY;
  1902. var zz = rotationZ * rotationZ;
  1903. var xy = rotationX * rotationY;
  1904. var zw = rotationZ * rotationW;
  1905. var zx = rotationZ * rotationX;
  1906. var yw = rotationY * rotationW;
  1907. var yz = rotationY * rotationZ;
  1908. var xw = rotationX * rotationW;
  1909. resultE[3] = resultE[7] = resultE[11] = resultE[12] = resultE[13] = resultE[14] = 0;
  1910. resultE[15] = 1.0;
  1911. resultE[0] = 1.0 - (2.0 * (yy + zz));
  1912. resultE[1] = 2.0 * (xy + zw);
  1913. resultE[2] = 2.0 * (zx - yw);
  1914. resultE[4] = 2.0 * (xy - zw);
  1915. resultE[5] = 1.0 - (2.0 * (zz + xx));
  1916. resultE[6] = 2.0 * (yz + xw);
  1917. resultE[8] = 2.0 * (zx + yw);
  1918. resultE[9] = 2.0 * (yz - xw);
  1919. resultE[10] = 1.0 - (2.0 * (yy + xx));
  1920. }
  1921. static createTranslate(trans, out) {
  1922. var oe = out.elements;
  1923. oe[4] = oe[8] = oe[1] = oe[9] = oe[2] = oe[6] = oe[3] = oe[7] = oe[11] = 0;
  1924. oe[0] = oe[5] = oe[10] = oe[15] = 1;
  1925. oe[12] = trans.x;
  1926. oe[13] = trans.y;
  1927. oe[14] = trans.z;
  1928. }
  1929. static createScaling(scale, out) {
  1930. var oe = out.elements;
  1931. oe[0] = scale.x;
  1932. oe[5] = scale.y;
  1933. oe[10] = scale.z;
  1934. 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;
  1935. oe[15] = 1;
  1936. }
  1937. static multiply(left, right, out) {
  1938. var l = right.elements;
  1939. var r = left.elements;
  1940. var e = out.elements;
  1941. var l11 = l[0], l12 = l[1], l13 = l[2], l14 = l[3];
  1942. var l21 = l[4], l22 = l[5], l23 = l[6], l24 = l[7];
  1943. var l31 = l[8], l32 = l[9], l33 = l[10], l34 = l[11];
  1944. var l41 = l[12], l42 = l[13], l43 = l[14], l44 = l[15];
  1945. var r11 = r[0], r12 = r[1], r13 = r[2], r14 = r[3];
  1946. var r21 = r[4], r22 = r[5], r23 = r[6], r24 = r[7];
  1947. var r31 = r[8], r32 = r[9], r33 = r[10], r34 = r[11];
  1948. var r41 = r[12], r42 = r[13], r43 = r[14], r44 = r[15];
  1949. e[0] = (l11 * r11) + (l12 * r21) + (l13 * r31) + (l14 * r41);
  1950. e[1] = (l11 * r12) + (l12 * r22) + (l13 * r32) + (l14 * r42);
  1951. e[2] = (l11 * r13) + (l12 * r23) + (l13 * r33) + (l14 * r43);
  1952. e[3] = (l11 * r14) + (l12 * r24) + (l13 * r34) + (l14 * r44);
  1953. e[4] = (l21 * r11) + (l22 * r21) + (l23 * r31) + (l24 * r41);
  1954. e[5] = (l21 * r12) + (l22 * r22) + (l23 * r32) + (l24 * r42);
  1955. e[6] = (l21 * r13) + (l22 * r23) + (l23 * r33) + (l24 * r43);
  1956. e[7] = (l21 * r14) + (l22 * r24) + (l23 * r34) + (l24 * r44);
  1957. e[8] = (l31 * r11) + (l32 * r21) + (l33 * r31) + (l34 * r41);
  1958. e[9] = (l31 * r12) + (l32 * r22) + (l33 * r32) + (l34 * r42);
  1959. e[10] = (l31 * r13) + (l32 * r23) + (l33 * r33) + (l34 * r43);
  1960. e[11] = (l31 * r14) + (l32 * r24) + (l33 * r34) + (l34 * r44);
  1961. e[12] = (l41 * r11) + (l42 * r21) + (l43 * r31) + (l44 * r41);
  1962. e[13] = (l41 * r12) + (l42 * r22) + (l43 * r32) + (l44 * r42);
  1963. e[14] = (l41 * r13) + (l42 * r23) + (l43 * r33) + (l44 * r43);
  1964. e[15] = (l41 * r14) + (l42 * r24) + (l43 * r34) + (l44 * r44);
  1965. }
  1966. static multiplyForNative(left, right, out) {
  1967. Laya.LayaGL.instance.matrix4x4Multiply(left.elements, right.elements, out.elements);
  1968. }
  1969. static createFromQuaternion(rotation, out) {
  1970. var e = out.elements;
  1971. var x = rotation.x, y = rotation.y, z = rotation.z, w = rotation.w;
  1972. var x2 = x + x;
  1973. var y2 = y + y;
  1974. var z2 = z + z;
  1975. var xx = x * x2;
  1976. var yx = y * x2;
  1977. var yy = y * y2;
  1978. var zx = z * x2;
  1979. var zy = z * y2;
  1980. var zz = z * z2;
  1981. var wx = w * x2;
  1982. var wy = w * y2;
  1983. var wz = w * z2;
  1984. e[0] = 1 - yy - zz;
  1985. e[1] = yx + wz;
  1986. e[2] = zx - wy;
  1987. e[3] = 0;
  1988. e[4] = yx - wz;
  1989. e[5] = 1 - xx - zz;
  1990. e[6] = zy + wx;
  1991. e[7] = 0;
  1992. e[8] = zx + wy;
  1993. e[9] = zy - wx;
  1994. e[10] = 1 - xx - yy;
  1995. e[11] = 0;
  1996. e[12] = 0;
  1997. e[13] = 0;
  1998. e[14] = 0;
  1999. e[15] = 1;
  2000. }
  2001. static createAffineTransformation(trans, rot, scale, out) {
  2002. var oe = out.elements;
  2003. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  2004. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  2005. var wx = w * x2, wy = w * y2, wz = w * z2, sx = scale.x, sy = scale.y, sz = scale.z;
  2006. oe[0] = (1 - (yy + zz)) * sx;
  2007. oe[1] = (xy + wz) * sx;
  2008. oe[2] = (xz - wy) * sx;
  2009. oe[3] = 0;
  2010. oe[4] = (xy - wz) * sy;
  2011. oe[5] = (1 - (xx + zz)) * sy;
  2012. oe[6] = (yz + wx) * sy;
  2013. oe[7] = 0;
  2014. oe[8] = (xz + wy) * sz;
  2015. oe[9] = (yz - wx) * sz;
  2016. oe[10] = (1 - (xx + yy)) * sz;
  2017. oe[11] = 0;
  2018. oe[12] = trans.x;
  2019. oe[13] = trans.y;
  2020. oe[14] = trans.z;
  2021. oe[15] = 1;
  2022. }
  2023. static createLookAt(eye, target, up, out) {
  2024. var oE = out.elements;
  2025. var xaxis = Matrix4x4._tempVector0;
  2026. var yaxis = Matrix4x4._tempVector1;
  2027. var zaxis = Matrix4x4._tempVector2;
  2028. Vector3.subtract(eye, target, zaxis);
  2029. Vector3.normalize(zaxis, zaxis);
  2030. Vector3.cross(up, zaxis, xaxis);
  2031. Vector3.normalize(xaxis, xaxis);
  2032. Vector3.cross(zaxis, xaxis, yaxis);
  2033. out.identity();
  2034. oE[0] = xaxis.x;
  2035. oE[4] = xaxis.y;
  2036. oE[8] = xaxis.z;
  2037. oE[1] = yaxis.x;
  2038. oE[5] = yaxis.y;
  2039. oE[9] = yaxis.z;
  2040. oE[2] = zaxis.x;
  2041. oE[6] = zaxis.y;
  2042. oE[10] = zaxis.z;
  2043. oE[12] = -Vector3.dot(xaxis, eye);
  2044. oE[13] = -Vector3.dot(yaxis, eye);
  2045. oE[14] = -Vector3.dot(zaxis, eye);
  2046. }
  2047. static createPerspective(fov, aspect, znear, zfar, out) {
  2048. var yScale = 1.0 / Math.tan(fov * 0.5);
  2049. var xScale = yScale / aspect;
  2050. var halfWidth = znear / xScale;
  2051. var halfHeight = znear / yScale;
  2052. Matrix4x4.createPerspectiveOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, znear, zfar, out);
  2053. }
  2054. static createPerspectiveOffCenter(left, right, bottom, top, znear, zfar, out) {
  2055. var oe = out.elements;
  2056. var zRange = zfar / (zfar - znear);
  2057. oe[1] = oe[2] = oe[3] = oe[4] = oe[6] = oe[7] = oe[12] = oe[13] = oe[15] = 0;
  2058. oe[0] = 2.0 * znear / (right - left);
  2059. oe[5] = 2.0 * znear / (top - bottom);
  2060. oe[8] = (left + right) / (right - left);
  2061. oe[9] = (top + bottom) / (top - bottom);
  2062. oe[10] = -zRange;
  2063. oe[11] = -1.0;
  2064. oe[14] = -znear * zRange;
  2065. }
  2066. static createOrthoOffCenter(left, right, bottom, top, znear, zfar, out) {
  2067. var oe = out.elements;
  2068. var zRange = 1.0 / (zfar - znear);
  2069. oe[1] = oe[2] = oe[3] = oe[4] = oe[6] = oe[8] = oe[7] = oe[9] = oe[11] = 0;
  2070. oe[15] = 1;
  2071. oe[0] = 2.0 / (right - left);
  2072. oe[5] = 2.0 / (top - bottom);
  2073. oe[10] = -zRange;
  2074. oe[12] = (left + right) / (left - right);
  2075. oe[13] = (top + bottom) / (bottom - top);
  2076. oe[14] = -znear * zRange;
  2077. }
  2078. getElementByRowColumn(row, column) {
  2079. if (row < 0 || row > 3)
  2080. throw new Error("row Rows and columns for matrices run from 0 to 3, inclusive.");
  2081. if (column < 0 || column > 3)
  2082. throw new Error("column Rows and columns for matrices run from 0 to 3, inclusive.");
  2083. return this.elements[(row * 4) + column];
  2084. }
  2085. setElementByRowColumn(row, column, value) {
  2086. if (row < 0 || row > 3)
  2087. throw new Error("row Rows and columns for matrices run from 0 to 3, inclusive.");
  2088. if (column < 0 || column > 3)
  2089. throw new Error("column Rows and columns for matrices run from 0 to 3, inclusive.");
  2090. this.elements[(row * 4) + column] = value;
  2091. }
  2092. equalsOtherMatrix(other) {
  2093. var e = this.elements;
  2094. var oe = other.elements;
  2095. 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]));
  2096. }
  2097. decomposeTransRotScale(translation, rotation, scale) {
  2098. var rotationMatrix = Matrix4x4._tempMatrix4x4;
  2099. if (this.decomposeTransRotMatScale(translation, rotationMatrix, scale)) {
  2100. Quaternion.createFromMatrix4x4(rotationMatrix, rotation);
  2101. return true;
  2102. }
  2103. else {
  2104. rotation.identity();
  2105. return false;
  2106. }
  2107. }
  2108. decomposeTransRotMatScale(translation, rotationMatrix, scale) {
  2109. var e = this.elements;
  2110. var te = translation;
  2111. var re = rotationMatrix.elements;
  2112. var se = scale;
  2113. te.x = e[12];
  2114. te.y = e[13];
  2115. te.z = e[14];
  2116. var m11 = e[0], m12 = e[1], m13 = e[2];
  2117. var m21 = e[4], m22 = e[5], m23 = e[6];
  2118. var m31 = e[8], m32 = e[9], m33 = e[10];
  2119. var sX = se.x = Math.sqrt((m11 * m11) + (m12 * m12) + (m13 * m13));
  2120. var sY = se.y = Math.sqrt((m21 * m21) + (m22 * m22) + (m23 * m23));
  2121. var sZ = se.z = Math.sqrt((m31 * m31) + (m32 * m32) + (m33 * m33));
  2122. if (MathUtils3D.isZero(sX) || MathUtils3D.isZero(sY) || MathUtils3D.isZero(sZ)) {
  2123. 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;
  2124. re[0] = re[5] = re[10] = re[15] = 1;
  2125. return false;
  2126. }
  2127. var at = Matrix4x4._tempVector0;
  2128. at.x = m31 / sZ;
  2129. at.y = m32 / sZ;
  2130. at.z = m33 / sZ;
  2131. var tempRight = Matrix4x4._tempVector1;
  2132. tempRight.x = m11 / sX;
  2133. tempRight.y = m12 / sX;
  2134. tempRight.z = m13 / sX;
  2135. var up = Matrix4x4._tempVector2;
  2136. Vector3.cross(at, tempRight, up);
  2137. var right = Matrix4x4._tempVector1;
  2138. Vector3.cross(up, at, right);
  2139. re[3] = re[7] = re[11] = re[12] = re[13] = re[14] = 0;
  2140. re[15] = 1;
  2141. re[0] = right.x;
  2142. re[1] = right.y;
  2143. re[2] = right.z;
  2144. re[4] = up.x;
  2145. re[5] = up.y;
  2146. re[6] = up.z;
  2147. re[8] = at.x;
  2148. re[9] = at.y;
  2149. re[10] = at.z;
  2150. ((re[0] * m11 + re[1] * m12 + re[2] * m13) < 0.0) && (se.x = -sX);
  2151. ((re[4] * m21 + re[5] * m22 + re[6] * m23) < 0.0) && (se.y = -sY);
  2152. ((re[8] * m31 + re[9] * m32 + re[10] * m33) < 0.0) && (se.z = -sZ);
  2153. return true;
  2154. }
  2155. decomposeYawPitchRoll(yawPitchRoll) {
  2156. var pitch = Math.asin(-this.elements[9]);
  2157. yawPitchRoll.y = pitch;
  2158. var test = Math.cos(pitch);
  2159. if (test > MathUtils3D.zeroTolerance) {
  2160. yawPitchRoll.z = Math.atan2(this.elements[1], this.elements[5]);
  2161. yawPitchRoll.x = Math.atan2(this.elements[8], this.elements[10]);
  2162. }
  2163. else {
  2164. yawPitchRoll.z = Math.atan2(-this.elements[4], this.elements[0]);
  2165. yawPitchRoll.x = 0.0;
  2166. }
  2167. }
  2168. normalize() {
  2169. var v = this.elements;
  2170. var c = v[0], d = v[1], e = v[2], g = Math.sqrt(c * c + d * d + e * e);
  2171. if (g) {
  2172. if (g == 1)
  2173. return;
  2174. }
  2175. else {
  2176. v[0] = 0;
  2177. v[1] = 0;
  2178. v[2] = 0;
  2179. return;
  2180. }
  2181. g = 1 / g;
  2182. v[0] = c * g;
  2183. v[1] = d * g;
  2184. v[2] = e * g;
  2185. }
  2186. transpose() {
  2187. var e, t;
  2188. e = this.elements;
  2189. t = e[1];
  2190. e[1] = e[4];
  2191. e[4] = t;
  2192. t = e[2];
  2193. e[2] = e[8];
  2194. e[8] = t;
  2195. t = e[3];
  2196. e[3] = e[12];
  2197. e[12] = t;
  2198. t = e[6];
  2199. e[6] = e[9];
  2200. e[9] = t;
  2201. t = e[7];
  2202. e[7] = e[13];
  2203. e[13] = t;
  2204. t = e[11];
  2205. e[11] = e[14];
  2206. e[14] = t;
  2207. return this;
  2208. }
  2209. invert(out) {
  2210. var ae = this.elements;
  2211. var oe = out.elements;
  2212. 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;
  2213. if (Math.abs(det) === 0.0) {
  2214. return;
  2215. }
  2216. det = 1.0 / det;
  2217. oe[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  2218. oe[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  2219. oe[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  2220. oe[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  2221. oe[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  2222. oe[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  2223. oe[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  2224. oe[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  2225. oe[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  2226. oe[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  2227. oe[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  2228. oe[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  2229. oe[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  2230. oe[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  2231. oe[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  2232. oe[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  2233. }
  2234. static billboard(objectPosition, cameraPosition, cameraRight, cameraUp, cameraForward, mat) {
  2235. Vector3.subtract(objectPosition, cameraPosition, Matrix4x4._tempVector0);
  2236. var lengthSq = Vector3.scalarLengthSquared(Matrix4x4._tempVector0);
  2237. if (MathUtils3D.isZero(lengthSq)) {
  2238. Vector3.scale(cameraForward, -1, Matrix4x4._tempVector1);
  2239. Matrix4x4._tempVector1.cloneTo(Matrix4x4._tempVector0);
  2240. }
  2241. else {
  2242. Vector3.scale(Matrix4x4._tempVector0, 1 / Math.sqrt(lengthSq), Matrix4x4._tempVector0);
  2243. }
  2244. Vector3.cross(cameraUp, Matrix4x4._tempVector0, Matrix4x4._tempVector2);
  2245. Vector3.normalize(Matrix4x4._tempVector2, Matrix4x4._tempVector2);
  2246. Vector3.cross(Matrix4x4._tempVector0, Matrix4x4._tempVector2, Matrix4x4._tempVector3);
  2247. var crosse = Matrix4x4._tempVector2;
  2248. var finale = Matrix4x4._tempVector3;
  2249. var diffee = Matrix4x4._tempVector0;
  2250. var obpose = objectPosition;
  2251. var mate = mat.elements;
  2252. mate[0] = crosse.x;
  2253. mate[1] = crosse.y;
  2254. mate[2] = crosse.z;
  2255. mate[3] = 0.0;
  2256. mate[4] = finale.x;
  2257. mate[5] = finale.y;
  2258. mate[6] = finale.z;
  2259. mate[7] = 0.0;
  2260. mate[8] = diffee.x;
  2261. mate[9] = diffee.y;
  2262. mate[10] = diffee.z;
  2263. mate[11] = 0.0;
  2264. mate[12] = obpose.x;
  2265. mate[13] = obpose.y;
  2266. mate[14] = obpose.z;
  2267. mate[15] = 1.0;
  2268. }
  2269. identity() {
  2270. var e = this.elements;
  2271. 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;
  2272. e[0] = e[5] = e[10] = e[15] = 1;
  2273. }
  2274. cloneTo(destObject) {
  2275. var i, s, d;
  2276. s = this.elements;
  2277. d = destObject.elements;
  2278. if (s === d) {
  2279. return;
  2280. }
  2281. for (i = 0; i < 16; ++i) {
  2282. d[i] = s[i];
  2283. }
  2284. }
  2285. clone() {
  2286. var dest = new Matrix4x4();
  2287. this.cloneTo(dest);
  2288. return dest;
  2289. }
  2290. static translation(v3, out) {
  2291. var oe = out.elements;
  2292. oe[0] = oe[5] = oe[10] = oe[15] = 1;
  2293. oe[12] = v3.x;
  2294. oe[13] = v3.y;
  2295. oe[14] = v3.z;
  2296. }
  2297. getTranslationVector(out) {
  2298. var me = this.elements;
  2299. out.x = me[12];
  2300. out.y = me[13];
  2301. out.z = me[14];
  2302. }
  2303. setTranslationVector(translate) {
  2304. var me = this.elements;
  2305. var ve = translate;
  2306. me[12] = ve.x;
  2307. me[13] = ve.y;
  2308. me[14] = ve.z;
  2309. }
  2310. getForward(out) {
  2311. var me = this.elements;
  2312. out.x = -me[8];
  2313. out.y = -me[9];
  2314. out.z = -me[10];
  2315. }
  2316. setForward(forward) {
  2317. var me = this.elements;
  2318. me[8] = -forward.x;
  2319. me[9] = -forward.y;
  2320. me[10] = -forward.z;
  2321. }
  2322. }
  2323. Matrix4x4._tempMatrix4x4 = new Matrix4x4();
  2324. Matrix4x4.TEMPMatrix0 = new Matrix4x4();
  2325. Matrix4x4.TEMPMatrix1 = new Matrix4x4();
  2326. Matrix4x4._tempVector0 = new Vector3();
  2327. Matrix4x4._tempVector1 = new Vector3();
  2328. Matrix4x4._tempVector2 = new Vector3();
  2329. Matrix4x4._tempVector3 = new Vector3();
  2330. Matrix4x4._tempQuaternion = new Quaternion();
  2331. Matrix4x4.DEFAULT = new Matrix4x4();
  2332. Matrix4x4.ZERO = new Matrix4x4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2333. class ConchQuaternion {
  2334. constructor(x = 0, y = 0, z = 0, w = 1, nativeElements = null) {
  2335. var v;
  2336. if (nativeElements) {
  2337. v = nativeElements;
  2338. }
  2339. else {
  2340. v = new Float32Array(4);
  2341. }
  2342. v[0] = x;
  2343. v[1] = y;
  2344. v[2] = z;
  2345. v[3] = w;
  2346. this.elements = v;
  2347. }
  2348. static _dotArray(l, r) {
  2349. return l[0] * r[0] + l[1] * r[1] + l[2] * r[2] + l[3] * r[3];
  2350. }
  2351. static _normalizeArray(f, o) {
  2352. var x = f[0], y = f[1], z = f[2], w = f[3];
  2353. var len = x * x + y * y + z * z + w * w;
  2354. if (len > 0) {
  2355. len = 1 / Math.sqrt(len);
  2356. o[0] = x * len;
  2357. o[1] = y * len;
  2358. o[2] = z * len;
  2359. o[3] = w * len;
  2360. }
  2361. }
  2362. static _lerpArray(l, r, amount, o) {
  2363. var inverse = 1.0 - amount;
  2364. if (ConchQuaternion._dotArray(l, r) >= 0) {
  2365. o[0] = (inverse * l[0]) + (amount * r[0]);
  2366. o[1] = (inverse * l[1]) + (amount * r[1]);
  2367. o[2] = (inverse * l[2]) + (amount * r[2]);
  2368. o[3] = (inverse * l[3]) + (amount * r[3]);
  2369. }
  2370. else {
  2371. o[0] = (inverse * l[0]) - (amount * r[0]);
  2372. o[1] = (inverse * l[1]) - (amount * r[1]);
  2373. o[2] = (inverse * l[2]) - (amount * r[2]);
  2374. o[3] = (inverse * l[3]) - (amount * r[3]);
  2375. }
  2376. ConchQuaternion._normalizeArray(o, o);
  2377. }
  2378. static createFromYawPitchRoll(yaw, pitch, roll, out) {
  2379. var halfRoll = roll * 0.5;
  2380. var halfPitch = pitch * 0.5;
  2381. var halfYaw = yaw * 0.5;
  2382. var sinRoll = Math.sin(halfRoll);
  2383. var cosRoll = Math.cos(halfRoll);
  2384. var sinPitch = Math.sin(halfPitch);
  2385. var cosPitch = Math.cos(halfPitch);
  2386. var sinYaw = Math.sin(halfYaw);
  2387. var cosYaw = Math.cos(halfYaw);
  2388. var oe = out.elements;
  2389. oe[0] = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2390. oe[1] = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2391. oe[2] = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2392. oe[3] = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2393. }
  2394. static multiply(left, right, out) {
  2395. var le = left.elements;
  2396. var re = right.elements;
  2397. var oe = out.elements;
  2398. var lx = le[0];
  2399. var ly = le[1];
  2400. var lz = le[2];
  2401. var lw = le[3];
  2402. var rx = re[0];
  2403. var ry = re[1];
  2404. var rz = re[2];
  2405. var rw = re[3];
  2406. var a = (ly * rz - lz * ry);
  2407. var b = (lz * rx - lx * rz);
  2408. var c = (lx * ry - ly * rx);
  2409. var d = (lx * rx + ly * ry + lz * rz);
  2410. oe[0] = (lx * rw + rx * lw) + a;
  2411. oe[1] = (ly * rw + ry * lw) + b;
  2412. oe[2] = (lz * rw + rz * lw) + c;
  2413. oe[3] = lw * rw - d;
  2414. }
  2415. static arcTanAngle(x, y) {
  2416. if (x == 0) {
  2417. if (y == 1)
  2418. return Math.PI / 2;
  2419. return -Math.PI / 2;
  2420. }
  2421. if (x > 0)
  2422. return Math.atan(y / x);
  2423. if (x < 0) {
  2424. if (y > 0)
  2425. return Math.atan(y / x) + Math.PI;
  2426. return Math.atan(y / x) - Math.PI;
  2427. }
  2428. return 0;
  2429. }
  2430. static angleTo(from, location, angle) {
  2431. ConchVector3.subtract(location, from, ConchQuaternion.TEMPVector30);
  2432. ConchVector3.normalize(ConchQuaternion.TEMPVector30, ConchQuaternion.TEMPVector30);
  2433. angle.elements[0] = Math.asin(ConchQuaternion.TEMPVector30.y);
  2434. angle.elements[1] = ConchQuaternion.arcTanAngle(-ConchQuaternion.TEMPVector30.z, -ConchQuaternion.TEMPVector30.x);
  2435. }
  2436. static createFromAxisAngle(axis, rad, out) {
  2437. var e = out.elements;
  2438. var f = axis.elements;
  2439. rad = rad * 0.5;
  2440. var s = Math.sin(rad);
  2441. e[0] = s * f[0];
  2442. e[1] = s * f[1];
  2443. e[2] = s * f[2];
  2444. e[3] = Math.cos(rad);
  2445. }
  2446. static createFromMatrix3x3(sou, out) {
  2447. var e = out.elements;
  2448. var f = sou.elements;
  2449. var fTrace = f[0] + f[4] + f[8];
  2450. var fRoot;
  2451. if (fTrace > 0.0) {
  2452. fRoot = Math.sqrt(fTrace + 1.0);
  2453. e[3] = 0.5 * fRoot;
  2454. fRoot = 0.5 / fRoot;
  2455. e[0] = (f[5] - f[7]) * fRoot;
  2456. e[1] = (f[6] - f[2]) * fRoot;
  2457. e[2] = (f[1] - f[3]) * fRoot;
  2458. }
  2459. else {
  2460. var i = 0;
  2461. if (f[4] > f[0])
  2462. i = 1;
  2463. if (f[8] > f[i * 3 + i])
  2464. i = 2;
  2465. var j = (i + 1) % 3;
  2466. var k = (i + 2) % 3;
  2467. fRoot = Math.sqrt(f[i * 3 + i] - f[j * 3 + j] - f[k * 3 + k] + 1.0);
  2468. e[i] = 0.5 * fRoot;
  2469. fRoot = 0.5 / fRoot;
  2470. e[3] = (f[j * 3 + k] - f[k * 3 + j]) * fRoot;
  2471. e[j] = (f[j * 3 + i] + f[i * 3 + j]) * fRoot;
  2472. e[k] = (f[k * 3 + i] + f[i * 3 + k]) * fRoot;
  2473. }
  2474. return;
  2475. }
  2476. static createFromMatrix4x4(mat, out) {
  2477. var me = mat.elements;
  2478. var oe = out.elements;
  2479. var sqrt;
  2480. var half;
  2481. var scale = me[0] + me[5] + me[10];
  2482. if (scale > 0.0) {
  2483. sqrt = Math.sqrt(scale + 1.0);
  2484. oe[3] = sqrt * 0.5;
  2485. sqrt = 0.5 / sqrt;
  2486. oe[0] = (me[6] - me[9]) * sqrt;
  2487. oe[1] = (me[8] - me[2]) * sqrt;
  2488. oe[2] = (me[1] - me[4]) * sqrt;
  2489. }
  2490. else if ((me[0] >= me[5]) && (me[0] >= me[10])) {
  2491. sqrt = Math.sqrt(1.0 + me[0] - me[5] - me[10]);
  2492. half = 0.5 / sqrt;
  2493. oe[0] = 0.5 * sqrt;
  2494. oe[1] = (me[1] + me[4]) * half;
  2495. oe[2] = (me[2] + me[8]) * half;
  2496. oe[3] = (me[6] - me[9]) * half;
  2497. }
  2498. else if (me[5] > me[10]) {
  2499. sqrt = Math.sqrt(1.0 + me[5] - me[0] - me[10]);
  2500. half = 0.5 / sqrt;
  2501. oe[0] = (me[4] + me[1]) * half;
  2502. oe[1] = 0.5 * sqrt;
  2503. oe[2] = (me[9] + me[6]) * half;
  2504. oe[3] = (me[8] - me[2]) * half;
  2505. }
  2506. else {
  2507. sqrt = Math.sqrt(1.0 + me[10] - me[0] - me[5]);
  2508. half = 0.5 / sqrt;
  2509. oe[0] = (me[8] + me[2]) * half;
  2510. oe[1] = (me[9] + me[6]) * half;
  2511. oe[2] = 0.5 * sqrt;
  2512. oe[3] = (me[1] - me[4]) * half;
  2513. }
  2514. }
  2515. static slerp(left, right, t, out) {
  2516. var a = left.elements;
  2517. var b = right.elements;
  2518. var oe = out.elements;
  2519. 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];
  2520. var omega, cosom, sinom, scale0, scale1;
  2521. cosom = ax * bx + ay * by + az * bz + aw * bw;
  2522. if (cosom < 0.0) {
  2523. cosom = -cosom;
  2524. bx = -bx;
  2525. by = -by;
  2526. bz = -bz;
  2527. bw = -bw;
  2528. }
  2529. if ((1.0 - cosom) > 0.000001) {
  2530. omega = Math.acos(cosom);
  2531. sinom = Math.sin(omega);
  2532. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  2533. scale1 = Math.sin(t * omega) / sinom;
  2534. }
  2535. else {
  2536. scale0 = 1.0 - t;
  2537. scale1 = t;
  2538. }
  2539. oe[0] = scale0 * ax + scale1 * bx;
  2540. oe[1] = scale0 * ay + scale1 * by;
  2541. oe[2] = scale0 * az + scale1 * bz;
  2542. oe[3] = scale0 * aw + scale1 * bw;
  2543. return oe;
  2544. }
  2545. static lerp(left, right, amount, out) {
  2546. ConchQuaternion._lerpArray(left.elements, right.elements, amount, out.elements);
  2547. }
  2548. static add(left, right, out) {
  2549. var e = out.elements;
  2550. var f = left.elements;
  2551. var g = right.elements;
  2552. e[0] = f[0] + g[0];
  2553. e[1] = f[1] + g[1];
  2554. e[2] = f[2] + g[2];
  2555. e[3] = f[3] + g[3];
  2556. }
  2557. static dot(left, right) {
  2558. return ConchQuaternion._dotArray(left.elements, right.elements);
  2559. }
  2560. get x() {
  2561. return this.elements[0];
  2562. }
  2563. set x(value) {
  2564. this.elements[0] = value;
  2565. }
  2566. get y() {
  2567. return this.elements[1];
  2568. }
  2569. set y(value) {
  2570. this.elements[1] = value;
  2571. }
  2572. get z() {
  2573. return this.elements[2];
  2574. }
  2575. set z(value) {
  2576. this.elements[2] = value;
  2577. }
  2578. get w() {
  2579. return this.elements[3];
  2580. }
  2581. set w(value) {
  2582. this.elements[3] = value;
  2583. }
  2584. scaling(scaling, out) {
  2585. var e = out.elements;
  2586. var f = this.elements;
  2587. e[0] = f[0] * scaling;
  2588. e[1] = f[1] * scaling;
  2589. e[2] = f[2] * scaling;
  2590. e[3] = f[3] * scaling;
  2591. }
  2592. normalize(out) {
  2593. ConchQuaternion._normalizeArray(this.elements, out.elements);
  2594. }
  2595. length() {
  2596. var f = this.elements;
  2597. var x = f[0], y = f[1], z = f[2], w = f[3];
  2598. return Math.sqrt(x * x + y * y + z * z + w * w);
  2599. }
  2600. rotateX(rad, out) {
  2601. var e = out.elements;
  2602. var f = this.elements;
  2603. rad *= 0.5;
  2604. var ax = f[0], ay = f[1], az = f[2], aw = f[3];
  2605. var bx = Math.sin(rad), bw = Math.cos(rad);
  2606. e[0] = ax * bw + aw * bx;
  2607. e[1] = ay * bw + az * bx;
  2608. e[2] = az * bw - ay * bx;
  2609. e[3] = aw * bw - ax * bx;
  2610. }
  2611. rotateY(rad, out) {
  2612. var e = out.elements;
  2613. var f = this.elements;
  2614. rad *= 0.5;
  2615. var ax = f[0], ay = f[1], az = f[2], aw = f[3], by = Math.sin(rad), bw = Math.cos(rad);
  2616. e[0] = ax * bw - az * by;
  2617. e[1] = ay * bw + aw * by;
  2618. e[2] = az * bw + ax * by;
  2619. e[3] = aw * bw - ay * by;
  2620. }
  2621. rotateZ(rad, out) {
  2622. var e = out.elements;
  2623. var f = this.elements;
  2624. rad *= 0.5;
  2625. var ax = f[0], ay = f[1], az = f[2], aw = f[3], bz = Math.sin(rad), bw = Math.cos(rad);
  2626. e[0] = ax * bw + ay * bz;
  2627. e[1] = ay * bw - ax * bz;
  2628. e[2] = az * bw + aw * bz;
  2629. e[3] = aw * bw - az * bz;
  2630. }
  2631. getYawPitchRoll(out) {
  2632. ConchVector3.transformQuat(ConchVector3.ForwardRH, this, ConchQuaternion.TEMPVector31);
  2633. ConchVector3.transformQuat(ConchVector3.Up, this, ConchQuaternion.TEMPVector32);
  2634. var upe = ConchQuaternion.TEMPVector32.elements;
  2635. ConchQuaternion.angleTo(ConchVector3.ZERO, ConchQuaternion.TEMPVector31, ConchQuaternion.TEMPVector33);
  2636. var anglee = ConchQuaternion.TEMPVector33.elements;
  2637. if (anglee[0] == Math.PI / 2) {
  2638. anglee[1] = ConchQuaternion.arcTanAngle(upe[2], upe[0]);
  2639. anglee[2] = 0;
  2640. }
  2641. else if (anglee[0] == -Math.PI / 2) {
  2642. anglee[1] = ConchQuaternion.arcTanAngle(-upe[2], -upe[0]);
  2643. anglee[2] = 0;
  2644. }
  2645. else {
  2646. Matrix4x4.createRotationY(-anglee[1], ConchQuaternion.TEMPMatrix0);
  2647. Matrix4x4.createRotationX(-anglee[0], ConchQuaternion.TEMPMatrix1);
  2648. ConchVector3.transformCoordinate(ConchQuaternion.TEMPVector32, ConchQuaternion.TEMPMatrix0, ConchQuaternion.TEMPVector32);
  2649. ConchVector3.transformCoordinate(ConchQuaternion.TEMPVector32, ConchQuaternion.TEMPMatrix1, ConchQuaternion.TEMPVector32);
  2650. anglee[2] = ConchQuaternion.arcTanAngle(upe[1], -upe[0]);
  2651. }
  2652. if (anglee[1] <= -Math.PI)
  2653. anglee[1] = Math.PI;
  2654. if (anglee[2] <= -Math.PI)
  2655. anglee[2] = Math.PI;
  2656. if (anglee[1] >= Math.PI && anglee[2] >= Math.PI) {
  2657. anglee[1] = 0;
  2658. anglee[2] = 0;
  2659. anglee[0] = Math.PI - anglee[0];
  2660. }
  2661. var oe = out.elements;
  2662. oe[0] = anglee[1];
  2663. oe[1] = anglee[0];
  2664. oe[2] = anglee[2];
  2665. }
  2666. invert(out) {
  2667. var e = out.elements;
  2668. var f = this.elements;
  2669. var a0 = f[0], a1 = f[1], a2 = f[2], a3 = f[3];
  2670. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  2671. var invDot = dot ? 1.0 / dot : 0;
  2672. e[0] = -a0 * invDot;
  2673. e[1] = -a1 * invDot;
  2674. e[2] = -a2 * invDot;
  2675. e[3] = a3 * invDot;
  2676. }
  2677. identity() {
  2678. var e = this.elements;
  2679. e[0] = 0;
  2680. e[1] = 0;
  2681. e[2] = 0;
  2682. e[3] = 1;
  2683. }
  2684. fromArray(array, offset = 0) {
  2685. this.elements[0] = array[offset + 0];
  2686. this.elements[1] = array[offset + 1];
  2687. this.elements[2] = array[offset + 2];
  2688. this.elements[3] = array[offset + 3];
  2689. }
  2690. cloneTo(destObject) {
  2691. var i, s, d;
  2692. s = this.elements;
  2693. d = destObject.elements;
  2694. if (s === d) {
  2695. return;
  2696. }
  2697. for (i = 0; i < 4; ++i) {
  2698. d[i] = s[i];
  2699. }
  2700. }
  2701. clone() {
  2702. var dest = new ConchQuaternion();
  2703. this.cloneTo(dest);
  2704. return dest;
  2705. }
  2706. equals(b) {
  2707. var ae = this.elements;
  2708. var be = b.elements;
  2709. 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]);
  2710. }
  2711. static rotationLookAt(forward, up, out) {
  2712. ConchQuaternion.lookAt(ConchVector3.ZERO, forward, up, out);
  2713. }
  2714. static lookAt(eye, target, up, out) {
  2715. Matrix3x3.lookAt(eye, target, up, ConchQuaternion._tempMatrix3x3);
  2716. ConchQuaternion.rotationMatrix(ConchQuaternion._tempMatrix3x3, out);
  2717. }
  2718. lengthSquared() {
  2719. var x = this.elements[0];
  2720. var y = this.elements[1];
  2721. var z = this.elements[2];
  2722. var w = this.elements[3];
  2723. return (x * x) + (y * y) + (z * z) + (w * w);
  2724. }
  2725. static invert(value, out) {
  2726. var vE = value.elements;
  2727. var oE = out.elements;
  2728. var lengthSq = value.lengthSquared();
  2729. if (!MathUtils3D.isZero(lengthSq)) {
  2730. lengthSq = 1.0 / lengthSq;
  2731. oE[0] = -vE[0] * lengthSq;
  2732. oE[1] = -vE[1] * lengthSq;
  2733. oE[2] = -vE[2] * lengthSq;
  2734. oE[3] = vE[3] * lengthSq;
  2735. }
  2736. }
  2737. static rotationMatrix(matrix3x3, out) {
  2738. var me = matrix3x3.elements;
  2739. var m11 = me[0];
  2740. var m12 = me[1];
  2741. var m13 = me[2];
  2742. var m21 = me[3];
  2743. var m22 = me[4];
  2744. var m23 = me[5];
  2745. var m31 = me[6];
  2746. var m32 = me[7];
  2747. var m33 = me[8];
  2748. var oe = out.elements;
  2749. var sqrt, half;
  2750. var scale = m11 + m22 + m33;
  2751. if (scale > 0) {
  2752. sqrt = Math.sqrt(scale + 1);
  2753. oe[3] = sqrt * 0.5;
  2754. sqrt = 0.5 / sqrt;
  2755. oe[0] = (m23 - m32) * sqrt;
  2756. oe[1] = (m31 - m13) * sqrt;
  2757. oe[2] = (m12 - m21) * sqrt;
  2758. }
  2759. else if ((m11 >= m22) && (m11 >= m33)) {
  2760. sqrt = Math.sqrt(1 + m11 - m22 - m33);
  2761. half = 0.5 / sqrt;
  2762. oe[0] = 0.5 * sqrt;
  2763. oe[1] = (m12 + m21) * half;
  2764. oe[2] = (m13 + m31) * half;
  2765. oe[3] = (m23 - m32) * half;
  2766. }
  2767. else if (m22 > m33) {
  2768. sqrt = Math.sqrt(1 + m22 - m11 - m33);
  2769. half = 0.5 / sqrt;
  2770. oe[0] = (m21 + m12) * half;
  2771. oe[1] = 0.5 * sqrt;
  2772. oe[2] = (m32 + m23) * half;
  2773. oe[3] = (m31 - m13) * half;
  2774. }
  2775. else {
  2776. sqrt = Math.sqrt(1 + m33 - m11 - m22);
  2777. half = 0.5 / sqrt;
  2778. oe[0] = (m31 + m13) * half;
  2779. oe[1] = (m32 + m23) * half;
  2780. oe[2] = 0.5 * sqrt;
  2781. oe[3] = (m12 - m21) * half;
  2782. }
  2783. }
  2784. }
  2785. ConchQuaternion.TEMPVector30 = new ConchVector3();
  2786. ConchQuaternion.TEMPVector31 = new ConchVector3();
  2787. ConchQuaternion.TEMPVector32 = new ConchVector3();
  2788. ConchQuaternion.TEMPVector33 = new ConchVector3();
  2789. ConchQuaternion.TEMPMatrix0 = new Matrix4x4();
  2790. ConchQuaternion.TEMPMatrix1 = new Matrix4x4();
  2791. ConchQuaternion._tempMatrix3x3 = new Matrix3x3();
  2792. ConchQuaternion.DEFAULT = new ConchQuaternion();
  2793. ConchQuaternion.NAN = new ConchQuaternion(NaN, NaN, NaN, NaN);
  2794. class AnimationClipParser03 {
  2795. static READ_DATA() {
  2796. AnimationClipParser03._DATA.offset = AnimationClipParser03._reader.getUint32();
  2797. AnimationClipParser03._DATA.size = AnimationClipParser03._reader.getUint32();
  2798. }
  2799. static READ_BLOCK() {
  2800. var count = AnimationClipParser03._BLOCK.count = AnimationClipParser03._reader.getUint16();
  2801. var blockStarts = AnimationClipParser03._BLOCK.blockStarts = [];
  2802. var blockLengths = AnimationClipParser03._BLOCK.blockLengths = [];
  2803. for (var i = 0; i < count; i++) {
  2804. blockStarts.push(AnimationClipParser03._reader.getUint32());
  2805. blockLengths.push(AnimationClipParser03._reader.getUint32());
  2806. }
  2807. }
  2808. static READ_STRINGS() {
  2809. var offset = AnimationClipParser03._reader.getUint32();
  2810. var count = AnimationClipParser03._reader.getUint16();
  2811. var prePos = AnimationClipParser03._reader.pos;
  2812. AnimationClipParser03._reader.pos = offset + AnimationClipParser03._DATA.offset;
  2813. for (var i = 0; i < count; i++)
  2814. AnimationClipParser03._strings[i] = AnimationClipParser03._reader.readUTFString();
  2815. AnimationClipParser03._reader.pos = prePos;
  2816. }
  2817. static parse(clip, reader) {
  2818. AnimationClipParser03._animationClip = clip;
  2819. AnimationClipParser03._reader = reader;
  2820. var arrayBuffer = reader.__getBuffer();
  2821. AnimationClipParser03.READ_DATA();
  2822. AnimationClipParser03.READ_BLOCK();
  2823. AnimationClipParser03.READ_STRINGS();
  2824. for (var i = 0, n = AnimationClipParser03._BLOCK.count; i < n; i++) {
  2825. var index = reader.getUint16();
  2826. var blockName = AnimationClipParser03._strings[index];
  2827. var fn = AnimationClipParser03["READ_" + blockName];
  2828. if (fn == null)
  2829. throw new Error("model file err,no this function:" + index + " " + blockName);
  2830. else
  2831. fn.call(null);
  2832. }
  2833. }
  2834. static READ_ANIMATIONS() {
  2835. var i, j;
  2836. var node;
  2837. var reader = AnimationClipParser03._reader;
  2838. var buffer = reader.__getBuffer();
  2839. var startTimeTypes = [];
  2840. var startTimeTypeCount = reader.getUint16();
  2841. startTimeTypes.length = startTimeTypeCount;
  2842. for (i = 0; i < startTimeTypeCount; i++)
  2843. startTimeTypes[i] = reader.getFloat32();
  2844. var clip = AnimationClipParser03._animationClip;
  2845. clip.name = AnimationClipParser03._strings[reader.getUint16()];
  2846. var clipDur = clip._duration = reader.getFloat32();
  2847. clip.islooping = !!reader.getByte();
  2848. clip._frameRate = reader.getInt16();
  2849. var nodeCount = reader.getInt16();
  2850. var nodes = clip._nodes;
  2851. nodes.count = nodeCount;
  2852. var nodesMap = clip._nodesMap = {};
  2853. var nodesDic = clip._nodesDic = {};
  2854. for (i = 0; i < nodeCount; i++) {
  2855. node = new KeyframeNode();
  2856. nodes.setNodeByIndex(i, node);
  2857. node._indexInList = i;
  2858. var type = node.type = reader.getUint8();
  2859. var pathLength = reader.getUint16();
  2860. node._setOwnerPathCount(pathLength);
  2861. for (j = 0; j < pathLength; j++)
  2862. node._setOwnerPathByIndex(j, AnimationClipParser03._strings[reader.getUint16()]);
  2863. var nodePath = node._joinOwnerPath("/");
  2864. var mapArray = nodesMap[nodePath];
  2865. (mapArray) || (nodesMap[nodePath] = mapArray = []);
  2866. mapArray.push(node);
  2867. node.propertyOwner = AnimationClipParser03._strings[reader.getUint16()];
  2868. var propertyLength = reader.getUint16();
  2869. node._setPropertyCount(propertyLength);
  2870. for (j = 0; j < propertyLength; j++)
  2871. node._setPropertyByIndex(j, AnimationClipParser03._strings[reader.getUint16()]);
  2872. var fullPath = nodePath + "." + node.propertyOwner + "." + node._joinProperty(".");
  2873. nodesDic[fullPath] = node;
  2874. node.fullPath = fullPath;
  2875. var keyframeCount = reader.getUint16();
  2876. node._setKeyframeCount(keyframeCount);
  2877. var startTime;
  2878. switch (type) {
  2879. case 0:
  2880. break;
  2881. case 1:
  2882. case 3:
  2883. case 4:
  2884. node.data = Laya.Render.supportWebGLPlusAnimation ? new ConchVector3 : new Vector3();
  2885. break;
  2886. case 2:
  2887. node.data = Laya.Render.supportWebGLPlusAnimation ? new ConchQuaternion : new Quaternion();
  2888. break;
  2889. default:
  2890. throw "AnimationClipParser03:unknown type.";
  2891. }
  2892. for (j = 0; j < keyframeCount; j++) {
  2893. switch (type) {
  2894. case 0:
  2895. var floatKeyframe = new FloatKeyframe();
  2896. node._setKeyframeByIndex(j, floatKeyframe);
  2897. startTime = floatKeyframe.time = startTimeTypes[reader.getUint16()];
  2898. floatKeyframe.inTangent = reader.getFloat32();
  2899. floatKeyframe.outTangent = reader.getFloat32();
  2900. floatKeyframe.value = reader.getFloat32();
  2901. break;
  2902. case 1:
  2903. case 3:
  2904. case 4:
  2905. var floatArrayKeyframe = new Vector3Keyframe();
  2906. node._setKeyframeByIndex(j, floatArrayKeyframe);
  2907. startTime = floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  2908. if (Laya.Render.supportWebGLPlusAnimation) {
  2909. var data = floatArrayKeyframe.data = new Float32Array(3 * 3);
  2910. for (var k = 0; k < 3; k++)
  2911. data[k] = reader.getFloat32();
  2912. for (k = 0; k < 3; k++)
  2913. data[3 + k] = reader.getFloat32();
  2914. for (k = 0; k < 3; k++)
  2915. data[6 + k] = reader.getFloat32();
  2916. }
  2917. else {
  2918. var inTangent = floatArrayKeyframe.inTangent;
  2919. var outTangent = floatArrayKeyframe.outTangent;
  2920. var value = floatArrayKeyframe.value;
  2921. inTangent.x = reader.getFloat32();
  2922. inTangent.y = reader.getFloat32();
  2923. inTangent.z = reader.getFloat32();
  2924. outTangent.x = reader.getFloat32();
  2925. outTangent.y = reader.getFloat32();
  2926. outTangent.z = reader.getFloat32();
  2927. value.x = reader.getFloat32();
  2928. value.y = reader.getFloat32();
  2929. value.z = reader.getFloat32();
  2930. }
  2931. break;
  2932. case 2:
  2933. var quaArrayKeyframe = new QuaternionKeyframe();
  2934. node._setKeyframeByIndex(j, quaArrayKeyframe);
  2935. startTime = quaArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  2936. if (Laya.Render.supportWebGLPlusAnimation) {
  2937. data = quaArrayKeyframe.data = new Float32Array(3 * 4);
  2938. for (k = 0; k < 4; k++)
  2939. data[k] = reader.getFloat32();
  2940. for (k = 0; k < 4; k++)
  2941. data[4 + k] = reader.getFloat32();
  2942. for (k = 0; k < 4; k++)
  2943. data[8 + k] = reader.getFloat32();
  2944. }
  2945. else {
  2946. var inTangentQua = quaArrayKeyframe.inTangent;
  2947. var outTangentQua = quaArrayKeyframe.outTangent;
  2948. var valueQua = quaArrayKeyframe.value;
  2949. inTangentQua.x = reader.getFloat32();
  2950. inTangentQua.y = reader.getFloat32();
  2951. inTangentQua.z = reader.getFloat32();
  2952. inTangentQua.w = reader.getFloat32();
  2953. outTangentQua.x = reader.getFloat32();
  2954. outTangentQua.y = reader.getFloat32();
  2955. outTangentQua.z = reader.getFloat32();
  2956. outTangentQua.w = reader.getFloat32();
  2957. valueQua.x = reader.getFloat32();
  2958. valueQua.y = reader.getFloat32();
  2959. valueQua.z = reader.getFloat32();
  2960. valueQua.w = reader.getFloat32();
  2961. }
  2962. break;
  2963. default:
  2964. throw "AnimationClipParser03:unknown type.";
  2965. }
  2966. }
  2967. }
  2968. var eventCount = reader.getUint16();
  2969. for (i = 0; i < eventCount; i++) {
  2970. var event = new AnimationEvent();
  2971. event.time = Math.min(clipDur, reader.getFloat32());
  2972. event.eventName = AnimationClipParser03._strings[reader.getUint16()];
  2973. var params;
  2974. var paramCount = reader.getUint16();
  2975. (paramCount > 0) && (event.params = params = []);
  2976. for (j = 0; j < paramCount; j++) {
  2977. var eventType = reader.getByte();
  2978. switch (eventType) {
  2979. case 0:
  2980. params.push(!!reader.getByte());
  2981. break;
  2982. case 1:
  2983. params.push(reader.getInt32());
  2984. break;
  2985. case 2:
  2986. params.push(reader.getFloat32());
  2987. break;
  2988. case 3:
  2989. params.push(AnimationClipParser03._strings[reader.getUint16()]);
  2990. break;
  2991. default:
  2992. throw new Error("unknown type.");
  2993. }
  2994. }
  2995. clip.addEvent(event);
  2996. }
  2997. }
  2998. }
  2999. AnimationClipParser03._strings = [];
  3000. AnimationClipParser03._BLOCK = { count: 0 };
  3001. AnimationClipParser03._DATA = { offset: 0, size: 0 };
  3002. class HalfFloatUtils {
  3003. static __init__() {
  3004. for (var i = 0; i < 256; ++i) {
  3005. var e = i - 127;
  3006. if (e < -27) {
  3007. HalfFloatUtils._baseTable[i | 0x000] = 0x0000;
  3008. HalfFloatUtils._baseTable[i | 0x100] = 0x8000;
  3009. HalfFloatUtils._shiftTable[i | 0x000] = 24;
  3010. HalfFloatUtils._shiftTable[i | 0x100] = 24;
  3011. }
  3012. else if (e < -14) {
  3013. HalfFloatUtils._baseTable[i | 0x000] = 0x0400 >> (-e - 14);
  3014. HalfFloatUtils._baseTable[i | 0x100] = (0x0400 >> (-e - 14)) | 0x8000;
  3015. HalfFloatUtils._shiftTable[i | 0x000] = -e - 1;
  3016. HalfFloatUtils._shiftTable[i | 0x100] = -e - 1;
  3017. }
  3018. else if (e <= 15) {
  3019. HalfFloatUtils._baseTable[i | 0x000] = (e + 15) << 10;
  3020. HalfFloatUtils._baseTable[i | 0x100] = ((e + 15) << 10) | 0x8000;
  3021. HalfFloatUtils._shiftTable[i | 0x000] = 13;
  3022. HalfFloatUtils._shiftTable[i | 0x100] = 13;
  3023. }
  3024. else if (e < 128) {
  3025. HalfFloatUtils._baseTable[i | 0x000] = 0x7c00;
  3026. HalfFloatUtils._baseTable[i | 0x100] = 0xfc00;
  3027. HalfFloatUtils._shiftTable[i | 0x000] = 24;
  3028. HalfFloatUtils._shiftTable[i | 0x100] = 24;
  3029. }
  3030. else {
  3031. HalfFloatUtils._baseTable[i | 0x000] = 0x7c00;
  3032. HalfFloatUtils._baseTable[i | 0x100] = 0xfc00;
  3033. HalfFloatUtils._shiftTable[i | 0x000] = 13;
  3034. HalfFloatUtils._shiftTable[i | 0x100] = 13;
  3035. }
  3036. }
  3037. HalfFloatUtils._mantissaTable[0] = 0;
  3038. for (i = 1; i < 1024; ++i) {
  3039. var m = i << 13;
  3040. e = 0;
  3041. while ((m & 0x00800000) === 0) {
  3042. e -= 0x00800000;
  3043. m <<= 1;
  3044. }
  3045. m &= ~0x00800000;
  3046. e += 0x38800000;
  3047. HalfFloatUtils._mantissaTable[i] = m | e;
  3048. }
  3049. for (i = 1024; i < 2048; ++i) {
  3050. HalfFloatUtils._mantissaTable[i] = 0x38000000 + ((i - 1024) << 13);
  3051. }
  3052. HalfFloatUtils._exponentTable[0] = 0;
  3053. for (i = 1; i < 31; ++i) {
  3054. HalfFloatUtils._exponentTable[i] = i << 23;
  3055. }
  3056. HalfFloatUtils._exponentTable[31] = 0x47800000;
  3057. HalfFloatUtils._exponentTable[32] = 0x80000000;
  3058. for (i = 33; i < 63; ++i) {
  3059. HalfFloatUtils._exponentTable[i] = 0x80000000 + ((i - 32) << 23);
  3060. }
  3061. HalfFloatUtils._exponentTable[63] = 0xc7800000;
  3062. HalfFloatUtils._offsetTable[0] = 0;
  3063. for (i = 1; i < 64; ++i) {
  3064. if (i === 32) {
  3065. HalfFloatUtils._offsetTable[i] = 0;
  3066. }
  3067. else {
  3068. HalfFloatUtils._offsetTable[i] = 1024;
  3069. }
  3070. }
  3071. }
  3072. static roundToFloat16Bits(num) {
  3073. HalfFloatUtils._floatView[0] = num;
  3074. var f = HalfFloatUtils._uint32View[0];
  3075. var e = (f >> 23) & 0x1ff;
  3076. return HalfFloatUtils._baseTable[e] + ((f & 0x007fffff) >> HalfFloatUtils._shiftTable[e]);
  3077. }
  3078. static convertToNumber(float16bits) {
  3079. var m = float16bits >> 10;
  3080. HalfFloatUtils._uint32View[0] = HalfFloatUtils._mantissaTable[HalfFloatUtils._offsetTable[m] + (float16bits & 0x3ff)] + HalfFloatUtils._exponentTable[m];
  3081. return HalfFloatUtils._floatView[0];
  3082. }
  3083. }
  3084. HalfFloatUtils._buffer = new ArrayBuffer(4);
  3085. HalfFloatUtils._floatView = new Float32Array(HalfFloatUtils._buffer);
  3086. HalfFloatUtils._uint32View = new Uint32Array(HalfFloatUtils._buffer);
  3087. HalfFloatUtils._baseTable = new Uint32Array(512);
  3088. HalfFloatUtils._shiftTable = new Uint32Array(512);
  3089. HalfFloatUtils._mantissaTable = new Uint32Array(2048);
  3090. HalfFloatUtils._exponentTable = new Uint32Array(64);
  3091. HalfFloatUtils._offsetTable = new Uint32Array(64);
  3092. class AnimationClipParser04 {
  3093. static READ_DATA() {
  3094. AnimationClipParser04._DATA.offset = AnimationClipParser04._reader.getUint32();
  3095. AnimationClipParser04._DATA.size = AnimationClipParser04._reader.getUint32();
  3096. }
  3097. static READ_BLOCK() {
  3098. var count = AnimationClipParser04._BLOCK.count = AnimationClipParser04._reader.getUint16();
  3099. var blockStarts = AnimationClipParser04._BLOCK.blockStarts = [];
  3100. var blockLengths = AnimationClipParser04._BLOCK.blockLengths = [];
  3101. for (var i = 0; i < count; i++) {
  3102. blockStarts.push(AnimationClipParser04._reader.getUint32());
  3103. blockLengths.push(AnimationClipParser04._reader.getUint32());
  3104. }
  3105. }
  3106. static READ_STRINGS() {
  3107. var offset = AnimationClipParser04._reader.getUint32();
  3108. var count = AnimationClipParser04._reader.getUint16();
  3109. var prePos = AnimationClipParser04._reader.pos;
  3110. AnimationClipParser04._reader.pos = offset + AnimationClipParser04._DATA.offset;
  3111. for (var i = 0; i < count; i++)
  3112. AnimationClipParser04._strings[i] = AnimationClipParser04._reader.readUTFString();
  3113. AnimationClipParser04._reader.pos = prePos;
  3114. }
  3115. static parse(clip, reader, version) {
  3116. AnimationClipParser04._animationClip = clip;
  3117. AnimationClipParser04._reader = reader;
  3118. AnimationClipParser04._version = version;
  3119. AnimationClipParser04.READ_DATA();
  3120. AnimationClipParser04.READ_BLOCK();
  3121. AnimationClipParser04.READ_STRINGS();
  3122. for (var i = 0, n = AnimationClipParser04._BLOCK.count; i < n; i++) {
  3123. var index = reader.getUint16();
  3124. var blockName = AnimationClipParser04._strings[index];
  3125. var fn = AnimationClipParser04["READ_" + blockName];
  3126. if (fn == null)
  3127. throw new Error("model file err,no this function:" + index + " " + blockName);
  3128. else
  3129. fn.call(null);
  3130. }
  3131. AnimationClipParser04._version = null;
  3132. AnimationClipParser04._reader = null;
  3133. AnimationClipParser04._animationClip = null;
  3134. }
  3135. static READ_ANIMATIONS() {
  3136. var i, j;
  3137. var node;
  3138. var reader = AnimationClipParser04._reader;
  3139. var buffer = reader.__getBuffer();
  3140. var startTimeTypes = [];
  3141. var startTimeTypeCount = reader.getUint16();
  3142. startTimeTypes.length = startTimeTypeCount;
  3143. for (i = 0; i < startTimeTypeCount; i++)
  3144. startTimeTypes[i] = reader.getFloat32();
  3145. var clip = AnimationClipParser04._animationClip;
  3146. clip.name = AnimationClipParser04._strings[reader.getUint16()];
  3147. var clipDur = clip._duration = reader.getFloat32();
  3148. clip.islooping = !!reader.getByte();
  3149. clip._frameRate = reader.getInt16();
  3150. var nodeCount = reader.getInt16();
  3151. var nodes = clip._nodes;
  3152. nodes.count = nodeCount;
  3153. var nodesMap = clip._nodesMap = {};
  3154. var nodesDic = clip._nodesDic = {};
  3155. for (i = 0; i < nodeCount; i++) {
  3156. node = new KeyframeNode();
  3157. nodes.setNodeByIndex(i, node);
  3158. node._indexInList = i;
  3159. var type = node.type = reader.getUint8();
  3160. var pathLength = reader.getUint16();
  3161. node._setOwnerPathCount(pathLength);
  3162. for (j = 0; j < pathLength; j++)
  3163. node._setOwnerPathByIndex(j, AnimationClipParser04._strings[reader.getUint16()]);
  3164. var nodePath = node._joinOwnerPath("/");
  3165. var mapArray = nodesMap[nodePath];
  3166. (mapArray) || (nodesMap[nodePath] = mapArray = []);
  3167. mapArray.push(node);
  3168. node.propertyOwner = AnimationClipParser04._strings[reader.getUint16()];
  3169. var propertyLength = reader.getUint16();
  3170. node._setPropertyCount(propertyLength);
  3171. for (j = 0; j < propertyLength; j++)
  3172. node._setPropertyByIndex(j, AnimationClipParser04._strings[reader.getUint16()]);
  3173. var fullPath = nodePath + "." + node.propertyOwner + "." + node._joinProperty(".");
  3174. nodesDic[fullPath] = node;
  3175. node.fullPath = fullPath;
  3176. var keyframeCount = reader.getUint16();
  3177. node._setKeyframeCount(keyframeCount);
  3178. var startTime;
  3179. switch (type) {
  3180. case 0:
  3181. break;
  3182. case 1:
  3183. case 3:
  3184. case 4:
  3185. node.data = Laya.Render.supportWebGLPlusAnimation ? new ConchVector3 : new Vector3();
  3186. break;
  3187. case 2:
  3188. node.data = Laya.Render.supportWebGLPlusAnimation ? new ConchQuaternion : new Quaternion();
  3189. break;
  3190. default:
  3191. throw "AnimationClipParser04:unknown type.";
  3192. }
  3193. switch (AnimationClipParser04._version) {
  3194. case "LAYAANIMATION:04":
  3195. for (j = 0; j < keyframeCount; j++) {
  3196. switch (type) {
  3197. case 0:
  3198. var floatKeyframe = new FloatKeyframe();
  3199. node._setKeyframeByIndex(j, floatKeyframe);
  3200. startTime = floatKeyframe.time = startTimeTypes[reader.getUint16()];
  3201. floatKeyframe.inTangent = reader.getFloat32();
  3202. floatKeyframe.outTangent = reader.getFloat32();
  3203. floatKeyframe.value = reader.getFloat32();
  3204. break;
  3205. case 1:
  3206. case 3:
  3207. case 4:
  3208. var floatArrayKeyframe = new Vector3Keyframe();
  3209. node._setKeyframeByIndex(j, floatArrayKeyframe);
  3210. startTime = floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  3211. if (Laya.Render.supportWebGLPlusAnimation) {
  3212. var data = floatArrayKeyframe.data = new Float32Array(3 * 3);
  3213. for (var k = 0; k < 3; k++)
  3214. data[k] = reader.getFloat32();
  3215. for (k = 0; k < 3; k++)
  3216. data[3 + k] = reader.getFloat32();
  3217. for (k = 0; k < 3; k++)
  3218. data[6 + k] = reader.getFloat32();
  3219. }
  3220. else {
  3221. var inTangent = floatArrayKeyframe.inTangent;
  3222. var outTangent = floatArrayKeyframe.outTangent;
  3223. var value = floatArrayKeyframe.value;
  3224. inTangent.x = reader.getFloat32();
  3225. inTangent.y = reader.getFloat32();
  3226. inTangent.z = reader.getFloat32();
  3227. outTangent.x = reader.getFloat32();
  3228. outTangent.y = reader.getFloat32();
  3229. outTangent.z = reader.getFloat32();
  3230. value.x = reader.getFloat32();
  3231. value.y = reader.getFloat32();
  3232. value.z = reader.getFloat32();
  3233. }
  3234. break;
  3235. case 2:
  3236. var quaternionKeyframe = new QuaternionKeyframe();
  3237. node._setKeyframeByIndex(j, quaternionKeyframe);
  3238. startTime = quaternionKeyframe.time = startTimeTypes[reader.getUint16()];
  3239. if (Laya.Render.supportWebGLPlusAnimation) {
  3240. data = quaternionKeyframe.data = new Float32Array(3 * 4);
  3241. for (k = 0; k < 4; k++)
  3242. data[k] = reader.getFloat32();
  3243. for (k = 0; k < 4; k++)
  3244. data[4 + k] = reader.getFloat32();
  3245. for (k = 0; k < 4; k++)
  3246. data[8 + k] = reader.getFloat32();
  3247. }
  3248. else {
  3249. var inTangentQua = quaternionKeyframe.inTangent;
  3250. var outTangentQua = quaternionKeyframe.outTangent;
  3251. var valueQua = quaternionKeyframe.value;
  3252. inTangentQua.x = reader.getFloat32();
  3253. inTangentQua.y = reader.getFloat32();
  3254. inTangentQua.z = reader.getFloat32();
  3255. inTangentQua.w = reader.getFloat32();
  3256. outTangentQua.x = reader.getFloat32();
  3257. outTangentQua.y = reader.getFloat32();
  3258. outTangentQua.z = reader.getFloat32();
  3259. outTangentQua.w = reader.getFloat32();
  3260. valueQua.x = reader.getFloat32();
  3261. valueQua.y = reader.getFloat32();
  3262. valueQua.z = reader.getFloat32();
  3263. valueQua.w = reader.getFloat32();
  3264. }
  3265. break;
  3266. default:
  3267. throw "AnimationClipParser04:unknown type.";
  3268. }
  3269. }
  3270. break;
  3271. case "LAYAANIMATION:COMPRESSION_04":
  3272. for (j = 0; j < keyframeCount; j++) {
  3273. switch (type) {
  3274. case 0:
  3275. floatKeyframe = new FloatKeyframe();
  3276. node._setKeyframeByIndex(j, floatKeyframe);
  3277. startTime = floatKeyframe.time = startTimeTypes[reader.getUint16()];
  3278. floatKeyframe.inTangent = HalfFloatUtils.convertToNumber(reader.getUint16());
  3279. floatKeyframe.outTangent = HalfFloatUtils.convertToNumber(reader.getUint16());
  3280. floatKeyframe.value = HalfFloatUtils.convertToNumber(reader.getUint16());
  3281. break;
  3282. case 1:
  3283. case 3:
  3284. case 4:
  3285. floatArrayKeyframe = new Vector3Keyframe();
  3286. node._setKeyframeByIndex(j, floatArrayKeyframe);
  3287. startTime = floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  3288. if (Laya.Render.supportWebGLPlusAnimation) {
  3289. data = floatArrayKeyframe.data = new Float32Array(3 * 3);
  3290. for (k = 0; k < 3; k++)
  3291. data[k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  3292. for (k = 0; k < 3; k++)
  3293. data[3 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  3294. for (k = 0; k < 3; k++)
  3295. data[6 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  3296. }
  3297. else {
  3298. inTangent = floatArrayKeyframe.inTangent;
  3299. outTangent = floatArrayKeyframe.outTangent;
  3300. value = floatArrayKeyframe.value;
  3301. inTangent.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  3302. inTangent.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  3303. inTangent.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  3304. outTangent.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  3305. outTangent.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  3306. outTangent.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  3307. value.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  3308. value.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  3309. value.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  3310. }
  3311. break;
  3312. case 2:
  3313. quaternionKeyframe = new QuaternionKeyframe();
  3314. node._setKeyframeByIndex(j, quaternionKeyframe);
  3315. startTime = quaternionKeyframe.time = startTimeTypes[reader.getUint16()];
  3316. if (Laya.Render.supportWebGLPlusAnimation) {
  3317. data = quaternionKeyframe.data = new Float32Array(3 * 4);
  3318. for (k = 0; k < 4; k++)
  3319. data[k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  3320. for (k = 0; k < 4; k++)
  3321. data[4 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  3322. for (k = 0; k < 4; k++)
  3323. data[8 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  3324. }
  3325. else {
  3326. inTangentQua = quaternionKeyframe.inTangent;
  3327. outTangentQua = quaternionKeyframe.outTangent;
  3328. valueQua = quaternionKeyframe.value;
  3329. inTangentQua.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  3330. inTangentQua.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  3331. inTangentQua.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  3332. inTangentQua.w = HalfFloatUtils.convertToNumber(reader.getUint16());
  3333. outTangentQua.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  3334. outTangentQua.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  3335. outTangentQua.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  3336. outTangentQua.w = HalfFloatUtils.convertToNumber(reader.getUint16());
  3337. valueQua.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  3338. valueQua.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  3339. valueQua.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  3340. valueQua.w = HalfFloatUtils.convertToNumber(reader.getUint16());
  3341. }
  3342. break;
  3343. default:
  3344. throw "AnimationClipParser04:unknown type.";
  3345. }
  3346. }
  3347. break;
  3348. }
  3349. }
  3350. var eventCount = reader.getUint16();
  3351. for (i = 0; i < eventCount; i++) {
  3352. var event = new AnimationEvent();
  3353. event.time = Math.min(clipDur, reader.getFloat32());
  3354. event.eventName = AnimationClipParser04._strings[reader.getUint16()];
  3355. var params;
  3356. var paramCount = reader.getUint16();
  3357. (paramCount > 0) && (event.params = params = []);
  3358. for (j = 0; j < paramCount; j++) {
  3359. var eventType = reader.getByte();
  3360. switch (eventType) {
  3361. case 0:
  3362. params.push(!!reader.getByte());
  3363. break;
  3364. case 1:
  3365. params.push(reader.getInt32());
  3366. break;
  3367. case 2:
  3368. params.push(reader.getFloat32());
  3369. break;
  3370. case 3:
  3371. params.push(AnimationClipParser04._strings[reader.getUint16()]);
  3372. break;
  3373. default:
  3374. throw new Error("unknown type.");
  3375. }
  3376. }
  3377. clip.addEvent(event);
  3378. }
  3379. }
  3380. }
  3381. AnimationClipParser04._strings = [];
  3382. AnimationClipParser04._BLOCK = { count: 0 };
  3383. AnimationClipParser04._DATA = { offset: 0, size: 0 };
  3384. class KeyframeNodeList {
  3385. constructor() {
  3386. this._nodes = [];
  3387. }
  3388. get count() {
  3389. return this._nodes.length;
  3390. }
  3391. set count(value) {
  3392. this._nodes.length = value;
  3393. }
  3394. getNodeByIndex(index) {
  3395. return this._nodes[index];
  3396. }
  3397. setNodeByIndex(index, node) {
  3398. this._nodes[index] = node;
  3399. }
  3400. }
  3401. if (window.conch && window.conchKeyframeNodeList) {
  3402. KeyframeNodeList = window.conchKeyframeNodeList;
  3403. }
  3404. if (window.qq && window.qq.webglPlus) {
  3405. KeyframeNodeList = window.qq.webglPlus.conchKeyframeNodeList;
  3406. }
  3407. class TextureGenerator {
  3408. constructor() {
  3409. }
  3410. static lightAttenTexture(x, y, maxX, maxY, index, data) {
  3411. var sqrRange = x / maxX;
  3412. var atten = 1.0 / (1.0 + 25.0 * sqrRange);
  3413. if (sqrRange >= 0.64) {
  3414. if (sqrRange > 1.0) {
  3415. atten = 0;
  3416. }
  3417. else {
  3418. atten *= 1 - (sqrRange - 0.64) / (1 - 0.64);
  3419. }
  3420. }
  3421. data[index] = Math.floor(atten * 255.0 + 0.5);
  3422. }
  3423. static haloTexture(x, y, maxX, maxY, index, data) {
  3424. maxX >>= 1;
  3425. maxY >>= 1;
  3426. var xFac = (x - maxX) / maxX;
  3427. var yFac = (y - maxY) / maxY;
  3428. var sqrRange = xFac * xFac + yFac * yFac;
  3429. if (sqrRange > 1.0) {
  3430. sqrRange = 1.0;
  3431. }
  3432. data[index] = Math.floor((1.0 - sqrRange) * 255.0 + 0.5);
  3433. }
  3434. static _generateTexture2D(texture, textureWidth, textureHeight, func) {
  3435. var index = 0;
  3436. var size = 0;
  3437. switch (texture.format) {
  3438. case Laya.TextureFormat.R8G8B8:
  3439. size = 3;
  3440. break;
  3441. case Laya.TextureFormat.R8G8B8A8:
  3442. size = 4;
  3443. break;
  3444. case Laya.TextureFormat.Alpha8:
  3445. size = 1;
  3446. break;
  3447. default:
  3448. throw "GeneratedTexture._generateTexture: unkonw texture format.";
  3449. }
  3450. var data = new Uint8Array(textureWidth * textureHeight * size);
  3451. for (var y = 0; y < textureHeight; y++) {
  3452. for (var x = 0; x < textureWidth; x++) {
  3453. func(x, y, textureWidth, textureHeight, index, data);
  3454. index += size;
  3455. }
  3456. }
  3457. texture.setPixels(data);
  3458. }
  3459. }
  3460. class Utils3D {
  3461. static _createFloatTextureBuffer(width, height) {
  3462. var floatTex = new Laya.Texture2D(width, height, Laya.TextureFormat.R32G32B32A32, false, false);
  3463. floatTex.filterMode = Laya.BaseTexture.FILTERMODE_POINT;
  3464. floatTex.wrapModeU = Laya.BaseTexture.WARPMODE_CLAMP;
  3465. floatTex.wrapModeV = Laya.BaseTexture.WARPMODE_CLAMP;
  3466. floatTex.anisoLevel = 0;
  3467. return floatTex;
  3468. }
  3469. static _convertToLayaVec3(bVector, out, inverseX) {
  3470. out.x = inverseX ? -bVector.x() : bVector.x();
  3471. out.y = bVector.y();
  3472. out.z = bVector.z();
  3473. }
  3474. static _convertToBulletVec3(lVector, out, inverseX) {
  3475. out.setValue(inverseX ? -lVector.x : lVector.x, lVector.y, lVector.z);
  3476. }
  3477. static _rotationTransformScaleSkinAnimation(tx, ty, tz, qx, qy, qz, qw, sx, sy, sz, outArray, outOffset) {
  3478. var re = Utils3D._tempArray16_0;
  3479. var se = Utils3D._tempArray16_1;
  3480. var tse = Utils3D._tempArray16_2;
  3481. var x2 = qx + qx;
  3482. var y2 = qy + qy;
  3483. var z2 = qz + qz;
  3484. var xx = qx * x2;
  3485. var yx = qy * x2;
  3486. var yy = qy * y2;
  3487. var zx = qz * x2;
  3488. var zy = qz * y2;
  3489. var zz = qz * z2;
  3490. var wx = qw * x2;
  3491. var wy = qw * y2;
  3492. var wz = qw * z2;
  3493. re[15] = 1;
  3494. re[0] = 1 - yy - zz;
  3495. re[1] = yx + wz;
  3496. re[2] = zx - wy;
  3497. re[4] = yx - wz;
  3498. re[5] = 1 - xx - zz;
  3499. re[6] = zy + wx;
  3500. re[8] = zx + wy;
  3501. re[9] = zy - wx;
  3502. re[10] = 1 - xx - yy;
  3503. se[15] = 1;
  3504. se[0] = sx;
  3505. se[5] = sy;
  3506. se[10] = sz;
  3507. var i, ai0, ai1, ai2, ai3;
  3508. for (i = 0; i < 4; i++) {
  3509. ai0 = re[i];
  3510. ai1 = re[i + 4];
  3511. ai2 = re[i + 8];
  3512. ai3 = re[i + 12];
  3513. tse[i] = ai0;
  3514. tse[i + 4] = ai1;
  3515. tse[i + 8] = ai2;
  3516. tse[i + 12] = ai0 * tx + ai1 * ty + ai2 * tz + ai3;
  3517. }
  3518. for (i = 0; i < 4; i++) {
  3519. ai0 = tse[i];
  3520. ai1 = tse[i + 4];
  3521. ai2 = tse[i + 8];
  3522. ai3 = tse[i + 12];
  3523. outArray[i + outOffset] = ai0 * se[0] + ai1 * se[1] + ai2 * se[2] + ai3 * se[3];
  3524. outArray[i + outOffset + 4] = ai0 * se[4] + ai1 * se[5] + ai2 * se[6] + ai3 * se[7];
  3525. outArray[i + outOffset + 8] = ai0 * se[8] + ai1 * se[9] + ai2 * se[10] + ai3 * se[11];
  3526. outArray[i + outOffset + 12] = ai0 * se[12] + ai1 * se[13] + ai2 * se[14] + ai3 * se[15];
  3527. }
  3528. }
  3529. static _computeBoneAndAnimationDatasByBindPoseMatrxix(bones, curData, inverGlobalBindPose, outBonesDatas, outAnimationDatas, boneIndexToMesh) {
  3530. var offset = 0;
  3531. var matOffset = 0;
  3532. var i;
  3533. var parentOffset;
  3534. var boneLength = bones.length;
  3535. for (i = 0; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++) {
  3536. 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);
  3537. if (i != 0) {
  3538. parentOffset = bones[i].parentIndex * 16;
  3539. Utils3D.mulMatrixByArray(outBonesDatas, parentOffset, outBonesDatas, matOffset, outBonesDatas, matOffset);
  3540. }
  3541. }
  3542. var n = inverGlobalBindPose.length;
  3543. for (i = 0; i < n; i++) {
  3544. Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas, boneIndexToMesh[i] * 16, inverGlobalBindPose[i], outAnimationDatas, i * 16);
  3545. }
  3546. }
  3547. static _computeAnimationDatasByArrayAndMatrixFast(inverGlobalBindPose, bonesDatas, outAnimationDatas, boneIndexToMesh) {
  3548. for (var i = 0, n = inverGlobalBindPose.length; i < n; i++)
  3549. Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas, boneIndexToMesh[i] * 16, inverGlobalBindPose[i], outAnimationDatas, i * 16);
  3550. }
  3551. static _computeBoneAndAnimationDatasByBindPoseMatrxixOld(bones, curData, inverGlobalBindPose, outBonesDatas, outAnimationDatas) {
  3552. var offset = 0;
  3553. var matOffset = 0;
  3554. var i;
  3555. var parentOffset;
  3556. var boneLength = bones.length;
  3557. for (i = 0; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++) {
  3558. 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);
  3559. if (i != 0) {
  3560. parentOffset = bones[i].parentIndex * 16;
  3561. Utils3D.mulMatrixByArray(outBonesDatas, parentOffset, outBonesDatas, matOffset, outBonesDatas, matOffset);
  3562. }
  3563. }
  3564. var n = inverGlobalBindPose.length;
  3565. for (i = 0; i < n; i++) {
  3566. var arrayOffset = i * 16;
  3567. Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas, arrayOffset, inverGlobalBindPose[i], outAnimationDatas, arrayOffset);
  3568. }
  3569. }
  3570. static _computeAnimationDatasByArrayAndMatrixFastOld(inverGlobalBindPose, bonesDatas, outAnimationDatas) {
  3571. var n = inverGlobalBindPose.length;
  3572. for (var i = 0; i < n; i++) {
  3573. var arrayOffset = i * 16;
  3574. Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas, arrayOffset, inverGlobalBindPose[i], outAnimationDatas, arrayOffset);
  3575. }
  3576. }
  3577. static _computeRootAnimationData(bones, curData, animationDatas) {
  3578. for (var i = 0, offset = 0, matOffset = 0, boneLength = bones.length; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++)
  3579. 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);
  3580. }
  3581. static transformVector3ArrayByQuat(sourceArray, sourceOffset, rotation, outArray, outOffset) {
  3582. 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;
  3583. outArray[outOffset] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  3584. outArray[outOffset + 1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  3585. outArray[outOffset + 2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  3586. }
  3587. static mulMatrixByArray(leftArray, leftOffset, rightArray, rightOffset, outArray, outOffset) {
  3588. var i, ai0, ai1, ai2, ai3;
  3589. if (outArray === rightArray) {
  3590. rightArray = Utils3D._tempArray16_3;
  3591. for (i = 0; i < 16; ++i) {
  3592. rightArray[i] = outArray[outOffset + i];
  3593. }
  3594. rightOffset = 0;
  3595. }
  3596. for (i = 0; i < 4; i++) {
  3597. ai0 = leftArray[leftOffset + i];
  3598. ai1 = leftArray[leftOffset + i + 4];
  3599. ai2 = leftArray[leftOffset + i + 8];
  3600. ai3 = leftArray[leftOffset + i + 12];
  3601. outArray[outOffset + i] = ai0 * rightArray[rightOffset + 0] + ai1 * rightArray[rightOffset + 1] + ai2 * rightArray[rightOffset + 2] + ai3 * rightArray[rightOffset + 3];
  3602. outArray[outOffset + i + 4] = ai0 * rightArray[rightOffset + 4] + ai1 * rightArray[rightOffset + 5] + ai2 * rightArray[rightOffset + 6] + ai3 * rightArray[rightOffset + 7];
  3603. outArray[outOffset + i + 8] = ai0 * rightArray[rightOffset + 8] + ai1 * rightArray[rightOffset + 9] + ai2 * rightArray[rightOffset + 10] + ai3 * rightArray[rightOffset + 11];
  3604. outArray[outOffset + i + 12] = ai0 * rightArray[rightOffset + 12] + ai1 * rightArray[rightOffset + 13] + ai2 * rightArray[rightOffset + 14] + ai3 * rightArray[rightOffset + 15];
  3605. }
  3606. }
  3607. static mulMatrixByArrayFast(leftArray, leftOffset, rightArray, rightOffset, outArray, outOffset) {
  3608. var i, ai0, ai1, ai2, ai3;
  3609. for (i = 0; i < 4; i++) {
  3610. ai0 = leftArray[leftOffset + i];
  3611. ai1 = leftArray[leftOffset + i + 4];
  3612. ai2 = leftArray[leftOffset + i + 8];
  3613. ai3 = leftArray[leftOffset + i + 12];
  3614. outArray[outOffset + i] = ai0 * rightArray[rightOffset + 0] + ai1 * rightArray[rightOffset + 1] + ai2 * rightArray[rightOffset + 2] + ai3 * rightArray[rightOffset + 3];
  3615. outArray[outOffset + i + 4] = ai0 * rightArray[rightOffset + 4] + ai1 * rightArray[rightOffset + 5] + ai2 * rightArray[rightOffset + 6] + ai3 * rightArray[rightOffset + 7];
  3616. outArray[outOffset + i + 8] = ai0 * rightArray[rightOffset + 8] + ai1 * rightArray[rightOffset + 9] + ai2 * rightArray[rightOffset + 10] + ai3 * rightArray[rightOffset + 11];
  3617. outArray[outOffset + i + 12] = ai0 * rightArray[rightOffset + 12] + ai1 * rightArray[rightOffset + 13] + ai2 * rightArray[rightOffset + 14] + ai3 * rightArray[rightOffset + 15];
  3618. }
  3619. }
  3620. static mulMatrixByArrayAndMatrixFast(leftArray, leftOffset, rightMatrix, outArray, outOffset) {
  3621. var i, ai0, ai1, ai2, ai3;
  3622. var rightMatrixE = rightMatrix.elements;
  3623. var m11 = rightMatrixE[0], m12 = rightMatrixE[1], m13 = rightMatrixE[2], m14 = rightMatrixE[3];
  3624. var m21 = rightMatrixE[4], m22 = rightMatrixE[5], m23 = rightMatrixE[6], m24 = rightMatrixE[7];
  3625. var m31 = rightMatrixE[8], m32 = rightMatrixE[9], m33 = rightMatrixE[10], m34 = rightMatrixE[11];
  3626. var m41 = rightMatrixE[12], m42 = rightMatrixE[13], m43 = rightMatrixE[14], m44 = rightMatrixE[15];
  3627. var ai0LeftOffset = leftOffset;
  3628. var ai1LeftOffset = leftOffset + 4;
  3629. var ai2LeftOffset = leftOffset + 8;
  3630. var ai3LeftOffset = leftOffset + 12;
  3631. var ai0OutOffset = outOffset;
  3632. var ai1OutOffset = outOffset + 4;
  3633. var ai2OutOffset = outOffset + 8;
  3634. var ai3OutOffset = outOffset + 12;
  3635. for (i = 0; i < 4; i++) {
  3636. ai0 = leftArray[ai0LeftOffset + i];
  3637. ai1 = leftArray[ai1LeftOffset + i];
  3638. ai2 = leftArray[ai2LeftOffset + i];
  3639. ai3 = leftArray[ai3LeftOffset + i];
  3640. outArray[ai0OutOffset + i] = ai0 * m11 + ai1 * m12 + ai2 * m13 + ai3 * m14;
  3641. outArray[ai1OutOffset + i] = ai0 * m21 + ai1 * m22 + ai2 * m23 + ai3 * m24;
  3642. outArray[ai2OutOffset + i] = ai0 * m31 + ai1 * m32 + ai2 * m33 + ai3 * m34;
  3643. outArray[ai3OutOffset + i] = ai0 * m41 + ai1 * m42 + ai2 * m43 + ai3 * m44;
  3644. }
  3645. }
  3646. static createAffineTransformationArray(tX, tY, tZ, rX, rY, rZ, rW, sX, sY, sZ, outArray, outOffset) {
  3647. var x2 = rX + rX, y2 = rY + rY, z2 = rZ + rZ;
  3648. var xx = rX * x2, xy = rX * y2, xz = rX * z2, yy = rY * y2, yz = rY * z2, zz = rZ * z2;
  3649. var wx = rW * x2, wy = rW * y2, wz = rW * z2;
  3650. outArray[outOffset + 0] = (1 - (yy + zz)) * sX;
  3651. outArray[outOffset + 1] = (xy + wz) * sX;
  3652. outArray[outOffset + 2] = (xz - wy) * sX;
  3653. outArray[outOffset + 3] = 0;
  3654. outArray[outOffset + 4] = (xy - wz) * sY;
  3655. outArray[outOffset + 5] = (1 - (xx + zz)) * sY;
  3656. outArray[outOffset + 6] = (yz + wx) * sY;
  3657. outArray[outOffset + 7] = 0;
  3658. outArray[outOffset + 8] = (xz + wy) * sZ;
  3659. outArray[outOffset + 9] = (yz - wx) * sZ;
  3660. outArray[outOffset + 10] = (1 - (xx + yy)) * sZ;
  3661. outArray[outOffset + 11] = 0;
  3662. outArray[outOffset + 12] = tX;
  3663. outArray[outOffset + 13] = tY;
  3664. outArray[outOffset + 14] = tZ;
  3665. outArray[outOffset + 15] = 1;
  3666. }
  3667. static transformVector3ArrayToVector3ArrayCoordinate(source, sourceOffset, transform, result, resultOffset) {
  3668. var coordinateX = source[sourceOffset + 0];
  3669. var coordinateY = source[sourceOffset + 1];
  3670. var coordinateZ = source[sourceOffset + 2];
  3671. var transformElem = transform.elements;
  3672. var w = ((coordinateX * transformElem[3]) + (coordinateY * transformElem[7]) + (coordinateZ * transformElem[11]) + transformElem[15]);
  3673. result[resultOffset] = (coordinateX * transformElem[0]) + (coordinateY * transformElem[4]) + (coordinateZ * transformElem[8]) + transformElem[12] / w;
  3674. result[resultOffset + 1] = (coordinateX * transformElem[1]) + (coordinateY * transformElem[5]) + (coordinateZ * transformElem[9]) + transformElem[13] / w;
  3675. result[resultOffset + 2] = (coordinateX * transformElem[2]) + (coordinateY * transformElem[6]) + (coordinateZ * transformElem[10]) + transformElem[14] / w;
  3676. }
  3677. static transformLightingMapTexcoordArray(source, sourceOffset, lightingMapScaleOffset, result, resultOffset) {
  3678. result[resultOffset + 0] = source[sourceOffset + 0] * lightingMapScaleOffset.x + lightingMapScaleOffset.z;
  3679. result[resultOffset + 1] = 1.0 - ((1.0 - source[sourceOffset + 1]) * lightingMapScaleOffset.y + lightingMapScaleOffset.w);
  3680. }
  3681. static getURLVerion(url) {
  3682. var index = url.indexOf("?");
  3683. return index >= 0 ? url.substr(index) : null;
  3684. }
  3685. static _createAffineTransformationArray(trans, rot, scale, outE) {
  3686. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  3687. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  3688. var wx = w * x2, wy = w * y2, wz = w * z2, sx = scale.x, sy = scale.y, sz = scale.z;
  3689. outE[0] = (1 - (yy + zz)) * sx;
  3690. outE[1] = (xy + wz) * sx;
  3691. outE[2] = (xz - wy) * sx;
  3692. outE[3] = 0;
  3693. outE[4] = (xy - wz) * sy;
  3694. outE[5] = (1 - (xx + zz)) * sy;
  3695. outE[6] = (yz + wx) * sy;
  3696. outE[7] = 0;
  3697. outE[8] = (xz + wy) * sz;
  3698. outE[9] = (yz - wx) * sz;
  3699. outE[10] = (1 - (xx + yy)) * sz;
  3700. outE[11] = 0;
  3701. outE[12] = trans.x;
  3702. outE[13] = trans.y;
  3703. outE[14] = trans.z;
  3704. outE[15] = 1;
  3705. }
  3706. static _mulMatrixArray(leftMatrixE, rightMatrix, outArray, outOffset) {
  3707. var i, ai0, ai1, ai2, ai3;
  3708. var rightMatrixE = rightMatrix.elements;
  3709. var m11 = rightMatrixE[0], m12 = rightMatrixE[1], m13 = rightMatrixE[2], m14 = rightMatrixE[3];
  3710. var m21 = rightMatrixE[4], m22 = rightMatrixE[5], m23 = rightMatrixE[6], m24 = rightMatrixE[7];
  3711. var m31 = rightMatrixE[8], m32 = rightMatrixE[9], m33 = rightMatrixE[10], m34 = rightMatrixE[11];
  3712. var m41 = rightMatrixE[12], m42 = rightMatrixE[13], m43 = rightMatrixE[14], m44 = rightMatrixE[15];
  3713. var ai0OutOffset = outOffset;
  3714. var ai1OutOffset = outOffset + 4;
  3715. var ai2OutOffset = outOffset + 8;
  3716. var ai3OutOffset = outOffset + 12;
  3717. for (i = 0; i < 4; i++) {
  3718. ai0 = leftMatrixE[i];
  3719. ai1 = leftMatrixE[i + 4];
  3720. ai2 = leftMatrixE[i + 8];
  3721. ai3 = leftMatrixE[i + 12];
  3722. outArray[ai0OutOffset + i] = ai0 * m11 + ai1 * m12 + ai2 * m13 + ai3 * m14;
  3723. outArray[ai1OutOffset + i] = ai0 * m21 + ai1 * m22 + ai2 * m23 + ai3 * m24;
  3724. outArray[ai2OutOffset + i] = ai0 * m31 + ai1 * m32 + ai2 * m33 + ai3 * m34;
  3725. outArray[ai3OutOffset + i] = ai0 * m41 + ai1 * m42 + ai2 * m43 + ai3 * m44;
  3726. }
  3727. }
  3728. static arcTanAngle(x, y) {
  3729. if (x == 0) {
  3730. if (y == 1)
  3731. return Math.PI / 2;
  3732. return -Math.PI / 2;
  3733. }
  3734. if (x > 0)
  3735. return Math.atan(y / x);
  3736. if (x < 0) {
  3737. if (y > 0)
  3738. return Math.atan(y / x) + Math.PI;
  3739. return Math.atan(y / x) - Math.PI;
  3740. }
  3741. return 0;
  3742. }
  3743. static angleTo(from, location, angle) {
  3744. Vector3.subtract(location, from, Quaternion.TEMPVector30);
  3745. Vector3.normalize(Quaternion.TEMPVector30, Quaternion.TEMPVector30);
  3746. angle.x = Math.asin(Quaternion.TEMPVector30.y);
  3747. angle.y = Utils3D.arcTanAngle(-Quaternion.TEMPVector30.z, -Quaternion.TEMPVector30.x);
  3748. }
  3749. static transformQuat(source, rotation, out) {
  3750. var re = rotation;
  3751. 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;
  3752. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  3753. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  3754. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  3755. }
  3756. static quaternionWeight(f, weight, e) {
  3757. e.x = f.x * weight;
  3758. e.y = f.y * weight;
  3759. e.z = f.z * weight;
  3760. e.w = f.w;
  3761. }
  3762. static quaternionConjugate(value, result) {
  3763. result.x = -value.x;
  3764. result.y = -value.y;
  3765. result.z = -value.z;
  3766. result.w = value.w;
  3767. }
  3768. static scaleWeight(s, w, out) {
  3769. var sX = s.x, sY = s.y, sZ = s.z;
  3770. out.x = sX > 0 ? Math.pow(Math.abs(sX), w) : -Math.pow(Math.abs(sX), w);
  3771. out.y = sY > 0 ? Math.pow(Math.abs(sY), w) : -Math.pow(Math.abs(sY), w);
  3772. out.z = sZ > 0 ? Math.pow(Math.abs(sZ), w) : -Math.pow(Math.abs(sZ), w);
  3773. }
  3774. static scaleBlend(sa, sb, w, out) {
  3775. var saw = Utils3D._tempVector3_0;
  3776. var sbw = Utils3D._tempVector3_1;
  3777. Utils3D.scaleWeight(sa, 1.0 - w, saw);
  3778. Utils3D.scaleWeight(sb, w, sbw);
  3779. var sng = w > 0.5 ? sb : sa;
  3780. out.x = sng.x > 0 ? Math.abs(saw.x * sbw.x) : -Math.abs(saw.x * sbw.x);
  3781. out.y = sng.y > 0 ? Math.abs(saw.y * sbw.y) : -Math.abs(saw.y * sbw.y);
  3782. out.z = sng.z > 0 ? Math.abs(saw.z * sbw.z) : -Math.abs(saw.z * sbw.z);
  3783. }
  3784. static matrix4x4MultiplyFFF(a, b, e) {
  3785. var i, ai0, ai1, ai2, ai3;
  3786. if (e === b) {
  3787. b = new Float32Array(16);
  3788. for (i = 0; i < 16; ++i) {
  3789. b[i] = e[i];
  3790. }
  3791. }
  3792. var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
  3793. var b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7];
  3794. var b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11];
  3795. var b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];
  3796. for (i = 0; i < 4; i++) {
  3797. ai0 = a[i];
  3798. ai1 = a[i + 4];
  3799. ai2 = a[i + 8];
  3800. ai3 = a[i + 12];
  3801. e[i] = ai0 * b0 + ai1 * b1 + ai2 * b2 + ai3 * b3;
  3802. e[i + 4] = ai0 * b4 + ai1 * b5 + ai2 * b6 + ai3 * b7;
  3803. e[i + 8] = ai0 * b8 + ai1 * b9 + ai2 * b10 + ai3 * b11;
  3804. e[i + 12] = ai0 * b12 + ai1 * b13 + ai2 * b14 + ai3 * b15;
  3805. }
  3806. }
  3807. static matrix4x4MultiplyFFFForNative(a, b, e) {
  3808. Laya.LayaGL.instance.matrix4x4Multiply(a, b, e);
  3809. }
  3810. static matrix4x4MultiplyMFM(left, right, out) {
  3811. Utils3D.matrix4x4MultiplyFFF(left.elements, right, out.elements);
  3812. }
  3813. static _buildTexture2D(width, height, format, colorFunc, mipmaps = false) {
  3814. var texture = new Laya.Texture2D(width, height, format, mipmaps, true);
  3815. texture.anisoLevel = 1;
  3816. texture.filterMode = Laya.BaseTexture.FILTERMODE_POINT;
  3817. TextureGenerator._generateTexture2D(texture, width, height, colorFunc);
  3818. return texture;
  3819. }
  3820. static _drawBound(debugLine, boundBox, color) {
  3821. if (debugLine.lineCount + 12 > debugLine.maxLineCount)
  3822. debugLine.maxLineCount += 12;
  3823. var start = Utils3D._tempVector3_0;
  3824. var end = Utils3D._tempVector3_1;
  3825. var min = boundBox.min;
  3826. var max = boundBox.max;
  3827. start.setValue(min.x, min.y, min.z);
  3828. end.setValue(max.x, min.y, min.z);
  3829. debugLine.addLine(start, end, color, color);
  3830. start.setValue(min.x, min.y, min.z);
  3831. end.setValue(min.x, min.y, max.z);
  3832. debugLine.addLine(start, end, color, color);
  3833. start.setValue(max.x, min.y, min.z);
  3834. end.setValue(max.x, min.y, max.z);
  3835. debugLine.addLine(start, end, color, color);
  3836. start.setValue(min.x, min.y, max.z);
  3837. end.setValue(max.x, min.y, max.z);
  3838. debugLine.addLine(start, end, color, color);
  3839. start.setValue(min.x, min.y, min.z);
  3840. end.setValue(min.x, max.y, min.z);
  3841. debugLine.addLine(start, end, color, color);
  3842. start.setValue(min.x, min.y, max.z);
  3843. end.setValue(min.x, max.y, max.z);
  3844. debugLine.addLine(start, end, color, color);
  3845. start.setValue(max.x, min.y, min.z);
  3846. end.setValue(max.x, max.y, min.z);
  3847. debugLine.addLine(start, end, color, color);
  3848. start.setValue(max.x, min.y, max.z);
  3849. end.setValue(max.x, max.y, max.z);
  3850. debugLine.addLine(start, end, color, color);
  3851. start.setValue(min.x, max.y, min.z);
  3852. end.setValue(max.x, max.y, min.z);
  3853. debugLine.addLine(start, end, color, color);
  3854. start.setValue(min.x, max.y, min.z);
  3855. end.setValue(min.x, max.y, max.z);
  3856. debugLine.addLine(start, end, color, color);
  3857. start.setValue(max.x, max.y, min.z);
  3858. end.setValue(max.x, max.y, max.z);
  3859. debugLine.addLine(start, end, color, color);
  3860. start.setValue(min.x, max.y, max.z);
  3861. end.setValue(max.x, max.y, max.z);
  3862. debugLine.addLine(start, end, color, color);
  3863. }
  3864. static _getHierarchyPath(rootSprite, checkSprite, path) {
  3865. path.length = 0;
  3866. var sprite = checkSprite;
  3867. while (sprite !== rootSprite) {
  3868. var parent = sprite._parent;
  3869. if (parent)
  3870. path.push(parent.getChildIndex(sprite));
  3871. else
  3872. return null;
  3873. sprite = parent;
  3874. }
  3875. return path;
  3876. }
  3877. static _getNodeByHierarchyPath(rootSprite, invPath) {
  3878. var sprite = rootSprite;
  3879. for (var i = invPath.length - 1; i >= 0; i--) {
  3880. sprite = sprite.getChildAt(invPath[i]);
  3881. }
  3882. return sprite;
  3883. }
  3884. }
  3885. Utils3D._tempVector3_0 = new Vector3();
  3886. Utils3D._tempVector3_1 = new Vector3();
  3887. Utils3D._tempArray16_0 = new Float32Array(16);
  3888. Utils3D._tempArray16_1 = new Float32Array(16);
  3889. Utils3D._tempArray16_2 = new Float32Array(16);
  3890. Utils3D._tempArray16_3 = new Float32Array(16);
  3891. Utils3D._compIdToNode = new Object();
  3892. class AnimationClip extends Laya.Resource {
  3893. constructor() {
  3894. super();
  3895. this._nodes = new KeyframeNodeList();
  3896. this._animationEvents = [];
  3897. }
  3898. static _parse(data, propertyParams = null, constructParams = null) {
  3899. var clip = new AnimationClip();
  3900. var reader = new Laya.Byte(data);
  3901. var version = reader.readUTFString();
  3902. switch (version) {
  3903. case "LAYAANIMATION:03":
  3904. AnimationClipParser03.parse(clip, reader);
  3905. break;
  3906. case "LAYAANIMATION:04":
  3907. case "LAYAANIMATION:COMPRESSION_04":
  3908. AnimationClipParser04.parse(clip, reader, version);
  3909. break;
  3910. default:
  3911. throw "unknown animationClip version.";
  3912. }
  3913. return clip;
  3914. }
  3915. static load(url, complete) {
  3916. Laya.ILaya.loader.create(url, complete, null, AnimationClip.ANIMATIONCLIP);
  3917. }
  3918. duration() {
  3919. return this._duration;
  3920. }
  3921. _hermiteInterpolate(frame, nextFrame, t, dur) {
  3922. var t0 = frame.outTangent, t1 = nextFrame.inTangent;
  3923. if (Number.isFinite(t0) && Number.isFinite(t1)) {
  3924. var t2 = t * t;
  3925. var t3 = t2 * t;
  3926. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  3927. var b = t3 - 2.0 * t2 + t;
  3928. var c = t3 - t2;
  3929. var d = -2.0 * t3 + 3.0 * t2;
  3930. return a * frame.value + b * t0 * dur + c * t1 * dur + d * nextFrame.value;
  3931. }
  3932. else
  3933. return frame.value;
  3934. }
  3935. _hermiteInterpolateVector3(frame, nextFrame, t, dur, out) {
  3936. var p0 = frame.value;
  3937. var tan0 = frame.outTangent;
  3938. var p1 = nextFrame.value;
  3939. var tan1 = nextFrame.inTangent;
  3940. var t2 = t * t;
  3941. var t3 = t2 * t;
  3942. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  3943. var b = t3 - 2.0 * t2 + t;
  3944. var c = t3 - t2;
  3945. var d = -2.0 * t3 + 3.0 * t2;
  3946. var t0 = tan0.x, t1 = tan1.x;
  3947. if (Number.isFinite(t0) && Number.isFinite(t1))
  3948. out.x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x;
  3949. else
  3950. out.x = p0.x;
  3951. t0 = tan0.y, t1 = tan1.y;
  3952. if (Number.isFinite(t0) && Number.isFinite(t1))
  3953. out.y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y;
  3954. else
  3955. out.y = p0.y;
  3956. t0 = tan0.z, t1 = tan1.z;
  3957. if (Number.isFinite(t0) && Number.isFinite(t1))
  3958. out.z = a * p0.z + b * t0 * dur + c * t1 * dur + d * p1.z;
  3959. else
  3960. out.z = p0.z;
  3961. }
  3962. _hermiteInterpolateQuaternion(frame, nextFrame, t, dur, out) {
  3963. var p0 = frame.value;
  3964. var tan0 = frame.outTangent;
  3965. var p1 = nextFrame.value;
  3966. var tan1 = nextFrame.inTangent;
  3967. var t2 = t * t;
  3968. var t3 = t2 * t;
  3969. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  3970. var b = t3 - 2.0 * t2 + t;
  3971. var c = t3 - t2;
  3972. var d = -2.0 * t3 + 3.0 * t2;
  3973. var t0 = tan0.x, t1 = tan1.x;
  3974. if (Number.isFinite(t0) && Number.isFinite(t1))
  3975. out.x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x;
  3976. else
  3977. out.x = p0.x;
  3978. t0 = tan0.y, t1 = tan1.y;
  3979. if (Number.isFinite(t0) && Number.isFinite(t1))
  3980. out.y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y;
  3981. else
  3982. out.y = p0.y;
  3983. t0 = tan0.z, t1 = tan1.z;
  3984. if (Number.isFinite(t0) && Number.isFinite(t1))
  3985. out.z = a * p0.z + b * t0 * dur + c * t1 * dur + d * p1.z;
  3986. else
  3987. out.z = p0.z;
  3988. t0 = tan0.w, t1 = tan1.w;
  3989. if (Number.isFinite(t0) && Number.isFinite(t1))
  3990. out.w = a * p0.w + b * t0 * dur + c * t1 * dur + d * p1.w;
  3991. else
  3992. out.w = p0.w;
  3993. }
  3994. _evaluateClipDatasRealTime(nodes, playCurTime, realTimeCurrentFrameIndexes, addtive, frontPlay) {
  3995. for (var i = 0, n = nodes.count; i < n; i++) {
  3996. var node = nodes.getNodeByIndex(i);
  3997. var type = node.type;
  3998. var nextFrameIndex;
  3999. var keyFrames = node._keyFrames;
  4000. var keyFramesCount = keyFrames.length;
  4001. var frameIndex = realTimeCurrentFrameIndexes[i];
  4002. if (frontPlay) {
  4003. if ((frameIndex !== -1) && (playCurTime < keyFrames[frameIndex].time)) {
  4004. frameIndex = -1;
  4005. realTimeCurrentFrameIndexes[i] = frameIndex;
  4006. }
  4007. nextFrameIndex = frameIndex + 1;
  4008. while (nextFrameIndex < keyFramesCount) {
  4009. if (keyFrames[nextFrameIndex].time > playCurTime)
  4010. break;
  4011. frameIndex++;
  4012. nextFrameIndex++;
  4013. realTimeCurrentFrameIndexes[i] = frameIndex;
  4014. }
  4015. }
  4016. else {
  4017. nextFrameIndex = frameIndex + 1;
  4018. if ((nextFrameIndex !== keyFramesCount) && (playCurTime > keyFrames[nextFrameIndex].time)) {
  4019. frameIndex = keyFramesCount - 1;
  4020. realTimeCurrentFrameIndexes[i] = frameIndex;
  4021. }
  4022. nextFrameIndex = frameIndex + 1;
  4023. while (frameIndex > -1) {
  4024. if (keyFrames[frameIndex].time < playCurTime)
  4025. break;
  4026. frameIndex--;
  4027. nextFrameIndex--;
  4028. realTimeCurrentFrameIndexes[i] = frameIndex;
  4029. }
  4030. }
  4031. var isEnd = nextFrameIndex === keyFramesCount;
  4032. switch (type) {
  4033. case 0:
  4034. if (frameIndex !== -1) {
  4035. var frame = keyFrames[frameIndex];
  4036. if (isEnd) {
  4037. node.data = frame.value;
  4038. }
  4039. else {
  4040. var nextFarme = keyFrames[nextFrameIndex];
  4041. var d = nextFarme.time - frame.time;
  4042. var t;
  4043. if (d !== 0)
  4044. t = (playCurTime - frame.time) / d;
  4045. else
  4046. t = 0;
  4047. node.data = this._hermiteInterpolate(frame, nextFarme, t, d);
  4048. }
  4049. }
  4050. else {
  4051. node.data = keyFrames[0].value;
  4052. }
  4053. if (addtive)
  4054. node.data -= keyFrames[0].value;
  4055. break;
  4056. case 1:
  4057. case 4:
  4058. var clipData = node.data;
  4059. this._evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipData);
  4060. if (addtive) {
  4061. var firstFrameValue = keyFrames[0].value;
  4062. clipData.x -= firstFrameValue.x;
  4063. clipData.y -= firstFrameValue.y;
  4064. clipData.z -= firstFrameValue.z;
  4065. }
  4066. break;
  4067. case 2:
  4068. var clipQuat = node.data;
  4069. this._evaluateFrameNodeQuaternionDatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipQuat);
  4070. if (addtive) {
  4071. var tempQuat = AnimationClip._tempQuaternion0;
  4072. var firstFrameValueQua = keyFrames[0].value;
  4073. Utils3D.quaternionConjugate(firstFrameValueQua, tempQuat);
  4074. Quaternion.multiply(tempQuat, clipQuat, clipQuat);
  4075. }
  4076. break;
  4077. case 3:
  4078. clipData = node.data;
  4079. this._evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipData);
  4080. if (addtive) {
  4081. firstFrameValue = keyFrames[0].value;
  4082. clipData.x /= firstFrameValue.x;
  4083. clipData.y /= firstFrameValue.y;
  4084. clipData.z /= firstFrameValue.z;
  4085. }
  4086. break;
  4087. default:
  4088. throw "AnimationClip:unknown node type.";
  4089. }
  4090. }
  4091. }
  4092. _evaluateClipDatasRealTimeForNative(nodes, playCurTime, realTimeCurrentFrameIndexes, addtive) {
  4093. Laya.LayaGL.instance.evaluateClipDatasRealTime(nodes._nativeObj, playCurTime, realTimeCurrentFrameIndexes, addtive);
  4094. }
  4095. _evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, outDatas) {
  4096. if (frameIndex !== -1) {
  4097. var frame = keyFrames[frameIndex];
  4098. if (isEnd) {
  4099. var frameData = frame.value;
  4100. outDatas.x = frameData.x;
  4101. outDatas.y = frameData.y;
  4102. outDatas.z = frameData.z;
  4103. }
  4104. else {
  4105. var nextKeyFrame = keyFrames[frameIndex + 1];
  4106. var t;
  4107. var startTime = frame.time;
  4108. var d = nextKeyFrame.time - startTime;
  4109. if (d !== 0)
  4110. t = (playCurTime - startTime) / d;
  4111. else
  4112. t = 0;
  4113. this._hermiteInterpolateVector3(frame, nextKeyFrame, t, d, outDatas);
  4114. }
  4115. }
  4116. else {
  4117. var firstFrameDatas = keyFrames[0].value;
  4118. outDatas.x = firstFrameDatas.x;
  4119. outDatas.y = firstFrameDatas.y;
  4120. outDatas.z = firstFrameDatas.z;
  4121. }
  4122. }
  4123. _evaluateFrameNodeQuaternionDatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, outDatas) {
  4124. if (frameIndex !== -1) {
  4125. var frame = keyFrames[frameIndex];
  4126. if (isEnd) {
  4127. var frameData = frame.value;
  4128. outDatas.x = frameData.x;
  4129. outDatas.y = frameData.y;
  4130. outDatas.z = frameData.z;
  4131. outDatas.w = frameData.w;
  4132. }
  4133. else {
  4134. var nextKeyFrame = keyFrames[frameIndex + 1];
  4135. var t;
  4136. var startTime = frame.time;
  4137. var d = nextKeyFrame.time - startTime;
  4138. if (d !== 0)
  4139. t = (playCurTime - startTime) / d;
  4140. else
  4141. t = 0;
  4142. this._hermiteInterpolateQuaternion(frame, nextKeyFrame, t, d, outDatas);
  4143. }
  4144. }
  4145. else {
  4146. var firstFrameDatas = keyFrames[0].value;
  4147. outDatas.x = firstFrameDatas.x;
  4148. outDatas.y = firstFrameDatas.y;
  4149. outDatas.z = firstFrameDatas.z;
  4150. outDatas.w = firstFrameDatas.w;
  4151. }
  4152. }
  4153. _binarySearchEventIndex(time) {
  4154. var start = 0;
  4155. var end = this._animationEvents.length - 1;
  4156. var mid;
  4157. while (start <= end) {
  4158. mid = Math.floor((start + end) / 2);
  4159. var midValue = this._animationEvents[mid].time;
  4160. if (midValue == time)
  4161. return mid;
  4162. else if (midValue > time)
  4163. end = mid - 1;
  4164. else
  4165. start = mid + 1;
  4166. }
  4167. return start;
  4168. }
  4169. addEvent(event) {
  4170. var index = this._binarySearchEventIndex(event.time);
  4171. this._animationEvents.splice(index, 0, event);
  4172. }
  4173. _disposeResource() {
  4174. this._nodes = null;
  4175. this._nodesMap = null;
  4176. }
  4177. }
  4178. AnimationClip.ANIMATIONCLIP = "ANIMATIONCLIP";
  4179. AnimationClip._tempQuaternion0 = new Quaternion();
  4180. class AnimatorPlayState {
  4181. get normalizedTime() {
  4182. return this._normalizedTime;
  4183. }
  4184. get duration() {
  4185. return this._duration;
  4186. }
  4187. constructor() {
  4188. }
  4189. _resetPlayState(startTime) {
  4190. this._finish = false;
  4191. this._startPlayTime = startTime;
  4192. this._elapsedTime = startTime;
  4193. this._playEventIndex = 0;
  4194. this._lastIsFront = true;
  4195. }
  4196. _cloneTo(dest) {
  4197. dest._finish = this._finish;
  4198. dest._startPlayTime = this._startPlayTime;
  4199. dest._elapsedTime = this._elapsedTime;
  4200. dest._playEventIndex = this._playEventIndex;
  4201. dest._lastIsFront = this._lastIsFront;
  4202. }
  4203. }
  4204. class AnimatorControllerLayer {
  4205. constructor(name) {
  4206. this._defaultState = null;
  4207. this._referenceCount = 0;
  4208. this._statesMap = {};
  4209. this.playOnWake = true;
  4210. this._playType = -1;
  4211. this._crossMark = 0;
  4212. this._crossDuration = -1;
  4213. this._crossNodesOwnersIndicesMap = {};
  4214. this._crossNodesOwnersCount = 0;
  4215. this._crossNodesOwners = [];
  4216. this._currentPlayState = null;
  4217. this._states = [];
  4218. this._playStateInfo = new AnimatorPlayState();
  4219. this._crossPlayStateInfo = new AnimatorPlayState();
  4220. this._srcCrossClipNodeIndices = [];
  4221. this._destCrossClipNodeIndices = [];
  4222. this.name = name;
  4223. this.defaultWeight = 1.0;
  4224. this.blendingMode = AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  4225. }
  4226. get defaultState() {
  4227. return this._defaultState;
  4228. }
  4229. set defaultState(value) {
  4230. this._defaultState = value;
  4231. this._statesMap[value.name] = value;
  4232. }
  4233. _removeClip(clipStateInfos, statesMap, index, state) {
  4234. var clip = state._clip;
  4235. var clipStateInfo = clipStateInfos[index];
  4236. clipStateInfos.splice(index, 1);
  4237. delete statesMap[state.name];
  4238. if (this._animator) {
  4239. var frameNodes = clip._nodes;
  4240. var nodeOwners = clipStateInfo._nodeOwners;
  4241. clip._removeReference();
  4242. for (var i = 0, n = frameNodes.count; i < n; i++)
  4243. this._animator._removeKeyframeNodeOwner(nodeOwners, frameNodes.getNodeByIndex(i));
  4244. }
  4245. }
  4246. _getReferenceCount() {
  4247. return this._referenceCount;
  4248. }
  4249. _addReference(count = 1) {
  4250. for (var i = 0, n = this._states.length; i < n; i++)
  4251. this._states[i]._addReference(count);
  4252. this._referenceCount += count;
  4253. }
  4254. _removeReference(count = 1) {
  4255. for (var i = 0, n = this._states.length; i < n; i++)
  4256. this._states[i]._removeReference(count);
  4257. this._referenceCount -= count;
  4258. }
  4259. _clearReference() {
  4260. this._removeReference(-this._referenceCount);
  4261. }
  4262. getAnimatorState(name) {
  4263. var state = this._statesMap[name];
  4264. return state ? state : null;
  4265. }
  4266. addState(state) {
  4267. var stateName = state.name;
  4268. if (this._statesMap[stateName]) {
  4269. throw "AnimatorControllerLayer:this stat's name has exist.";
  4270. }
  4271. else {
  4272. this._statesMap[stateName] = state;
  4273. this._states.push(state);
  4274. if (this._animator) {
  4275. state._clip._addReference();
  4276. this._animator._getOwnersByClip(state);
  4277. }
  4278. }
  4279. }
  4280. removeState(state) {
  4281. var states = this._states;
  4282. var index = -1;
  4283. for (var i = 0, n = states.length; i < n; i++) {
  4284. if (states[i] === state) {
  4285. index = i;
  4286. break;
  4287. }
  4288. }
  4289. if (index !== -1)
  4290. this._removeClip(states, this._statesMap, index, state);
  4291. }
  4292. destroy() {
  4293. this._clearReference();
  4294. this._statesMap = null;
  4295. this._states = null;
  4296. this._playStateInfo = null;
  4297. this._crossPlayStateInfo = null;
  4298. this._defaultState = null;
  4299. }
  4300. cloneTo(destObject) {
  4301. var dest = destObject;
  4302. dest.name = this.name;
  4303. dest.blendingMode = this.blendingMode;
  4304. dest.defaultWeight = this.defaultWeight;
  4305. dest.playOnWake = this.playOnWake;
  4306. }
  4307. clone() {
  4308. var dest = new AnimatorControllerLayer(this.name);
  4309. this.cloneTo(dest);
  4310. return dest;
  4311. }
  4312. }
  4313. AnimatorControllerLayer.BLENDINGMODE_OVERRIDE = 0;
  4314. AnimatorControllerLayer.BLENDINGMODE_ADDTIVE = 1;
  4315. class AnimatorState {
  4316. constructor() {
  4317. this._referenceCount = 0;
  4318. this._clip = null;
  4319. this._nodeOwners = [];
  4320. this._currentFrameIndices = null;
  4321. this._scripts = null;
  4322. this.speed = 1.0;
  4323. this.clipStart = 0.0;
  4324. this.clipEnd = 1.0;
  4325. }
  4326. get clip() {
  4327. return this._clip;
  4328. }
  4329. set clip(value) {
  4330. if (this._clip !== value) {
  4331. if (this._clip)
  4332. (this._referenceCount > 0) && (this._clip._removeReference(this._referenceCount));
  4333. if (value) {
  4334. this._currentFrameIndices = new Int16Array(value._nodes.count);
  4335. this._resetFrameIndices();
  4336. (this._referenceCount > 0) && (this._clip._addReference(this._referenceCount));
  4337. }
  4338. this._clip = value;
  4339. }
  4340. }
  4341. _getReferenceCount() {
  4342. return this._referenceCount;
  4343. }
  4344. _addReference(count = 1) {
  4345. (this._clip) && (this._clip._addReference(count));
  4346. this._referenceCount += count;
  4347. }
  4348. _removeReference(count = 1) {
  4349. (this._clip) && (this._clip._removeReference(count));
  4350. this._referenceCount -= count;
  4351. }
  4352. _clearReference() {
  4353. this._removeReference(-this._referenceCount);
  4354. }
  4355. _resetFrameIndices() {
  4356. for (var i = 0, n = this._currentFrameIndices.length; i < n; i++)
  4357. this._currentFrameIndices[i] = -1;
  4358. }
  4359. addScript(type) {
  4360. var script = new type();
  4361. this._scripts = this._scripts || [];
  4362. this._scripts.push(script);
  4363. return script;
  4364. }
  4365. getScript(type) {
  4366. if (this._scripts) {
  4367. for (var i = 0, n = this._scripts.length; i < n; i++) {
  4368. var script = this._scripts[i];
  4369. if (script instanceof type)
  4370. return script;
  4371. }
  4372. }
  4373. return null;
  4374. }
  4375. getScripts(type) {
  4376. var coms;
  4377. if (this._scripts) {
  4378. for (var i = 0, n = this._scripts.length; i < n; i++) {
  4379. var script = this._scripts[i];
  4380. if (script instanceof type) {
  4381. coms = coms || [];
  4382. coms.push(script);
  4383. }
  4384. }
  4385. }
  4386. return coms;
  4387. }
  4388. cloneTo(destObject) {
  4389. var dest = destObject;
  4390. dest.name = this.name;
  4391. dest.speed = this.speed;
  4392. dest.clipStart = this.clipStart;
  4393. dest.clipEnd = this.clipEnd;
  4394. dest.clip = this._clip;
  4395. }
  4396. clone() {
  4397. var dest = new AnimatorState();
  4398. this.cloneTo(dest);
  4399. return dest;
  4400. }
  4401. }
  4402. class KeyframeNodeOwner {
  4403. constructor() {
  4404. this.indexInList = -1;
  4405. this.referenceCount = 0;
  4406. this.updateMark = -1;
  4407. this.type = -1;
  4408. this.fullPath = null;
  4409. this.propertyOwner = null;
  4410. this.property = null;
  4411. this.defaultValue = null;
  4412. this.crossFixedValue = null;
  4413. }
  4414. saveCrossFixedValue() {
  4415. var pro = this.propertyOwner;
  4416. if (pro) {
  4417. switch (this.type) {
  4418. case 0:
  4419. var proPat = this.property;
  4420. var m = proPat.length - 1;
  4421. for (var j = 0; j < m; j++) {
  4422. pro = pro[proPat[j]];
  4423. if (!pro)
  4424. break;
  4425. }
  4426. this.crossFixedValue = pro[proPat[m]];
  4427. break;
  4428. case 1:
  4429. var locPos = pro.localPosition;
  4430. this.crossFixedValue || (this.crossFixedValue = new Vector3());
  4431. this.crossFixedValue.x = locPos.x;
  4432. this.crossFixedValue.y = locPos.y;
  4433. this.crossFixedValue.z = locPos.z;
  4434. break;
  4435. case 2:
  4436. var locRot = pro.localRotation;
  4437. this.crossFixedValue || (this.crossFixedValue = new Quaternion());
  4438. this.crossFixedValue.x = locRot.x;
  4439. this.crossFixedValue.y = locRot.y;
  4440. this.crossFixedValue.z = locRot.z;
  4441. this.crossFixedValue.w = locRot.w;
  4442. break;
  4443. case 3:
  4444. var locSca = pro.localScale;
  4445. this.crossFixedValue || (this.crossFixedValue = new Vector3());
  4446. this.crossFixedValue.x = locSca.x;
  4447. this.crossFixedValue.y = locSca.y;
  4448. this.crossFixedValue.z = locSca.z;
  4449. break;
  4450. case 4:
  4451. var locEul = pro.localRotationEuler;
  4452. this.crossFixedValue || (this.crossFixedValue = new Vector3());
  4453. this.crossFixedValue.x = locEul.x;
  4454. this.crossFixedValue.y = locEul.y;
  4455. this.crossFixedValue.z = locEul.z;
  4456. break;
  4457. default:
  4458. throw "Animator:unknown type.";
  4459. }
  4460. }
  4461. }
  4462. }
  4463. class Animator extends Laya.Component {
  4464. constructor() {
  4465. super();
  4466. this._keyframeNodeOwners = [];
  4467. this._linkAvatarSpritesData = {};
  4468. this._linkAvatarSprites = [];
  4469. this._renderableSprites = [];
  4470. this.cullingMode = Animator.CULLINGMODE_CULLCOMPLETELY;
  4471. this._controllerLayers = [];
  4472. this._linkSprites = {};
  4473. this._speed = 1.0;
  4474. this._keyframeNodeOwnerMap = {};
  4475. this._updateMark = 0;
  4476. }
  4477. static _update(scene) {
  4478. var pool = scene._animatorPool;
  4479. var elements = pool.elements;
  4480. for (var i = 0, n = pool.length; i < n; i++) {
  4481. var animator = elements[i];
  4482. (animator && animator.enabled) && (animator._update());
  4483. }
  4484. }
  4485. get speed() {
  4486. return this._speed;
  4487. }
  4488. set speed(value) {
  4489. this._speed = value;
  4490. }
  4491. _linkToSprites(linkSprites) {
  4492. for (var k in linkSprites) {
  4493. var nodeOwner = this.owner;
  4494. var path = linkSprites[k];
  4495. for (var j = 0, m = path.length; j < m; j++) {
  4496. var p = path[j];
  4497. if (p === "") {
  4498. break;
  4499. }
  4500. else {
  4501. nodeOwner = nodeOwner.getChildByName(p);
  4502. if (!nodeOwner)
  4503. break;
  4504. }
  4505. }
  4506. (nodeOwner) && (this.linkSprite3DToAvatarNode(k, nodeOwner));
  4507. }
  4508. }
  4509. _addKeyframeNodeOwner(clipOwners, node, propertyOwner) {
  4510. var nodeIndex = node._indexInList;
  4511. var fullPath = node.fullPath;
  4512. var keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath];
  4513. if (keyframeNodeOwner) {
  4514. keyframeNodeOwner.referenceCount++;
  4515. clipOwners[nodeIndex] = keyframeNodeOwner;
  4516. }
  4517. else {
  4518. var property = propertyOwner;
  4519. for (var i = 0, n = node.propertyCount; i < n; i++) {
  4520. property = property[node.getPropertyByIndex(i)];
  4521. if (!property)
  4522. break;
  4523. }
  4524. keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath] = new KeyframeNodeOwner();
  4525. keyframeNodeOwner.fullPath = fullPath;
  4526. keyframeNodeOwner.indexInList = this._keyframeNodeOwners.length;
  4527. keyframeNodeOwner.referenceCount = 1;
  4528. keyframeNodeOwner.propertyOwner = propertyOwner;
  4529. var propertyCount = node.propertyCount;
  4530. var propertys = [];
  4531. for (i = 0; i < propertyCount; i++)
  4532. propertys[i] = node.getPropertyByIndex(i);
  4533. keyframeNodeOwner.property = propertys;
  4534. keyframeNodeOwner.type = node.type;
  4535. if (property) {
  4536. if (node.type === 0) {
  4537. keyframeNodeOwner.defaultValue = property;
  4538. }
  4539. else {
  4540. var defaultValue = new property.constructor();
  4541. property.cloneTo(defaultValue);
  4542. keyframeNodeOwner.defaultValue = defaultValue;
  4543. }
  4544. }
  4545. this._keyframeNodeOwners.push(keyframeNodeOwner);
  4546. clipOwners[nodeIndex] = keyframeNodeOwner;
  4547. }
  4548. }
  4549. _removeKeyframeNodeOwner(nodeOwners, node) {
  4550. var fullPath = node.fullPath;
  4551. var keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath];
  4552. if (keyframeNodeOwner) {
  4553. keyframeNodeOwner.referenceCount--;
  4554. if (keyframeNodeOwner.referenceCount === 0) {
  4555. delete this._keyframeNodeOwnerMap[fullPath];
  4556. this._keyframeNodeOwners.splice(this._keyframeNodeOwners.indexOf(keyframeNodeOwner), 1);
  4557. }
  4558. nodeOwners[node._indexInList] = null;
  4559. }
  4560. }
  4561. _getOwnersByClip(clipStateInfo) {
  4562. var frameNodes = clipStateInfo._clip._nodes;
  4563. var frameNodesCount = frameNodes.count;
  4564. var nodeOwners = clipStateInfo._nodeOwners;
  4565. nodeOwners.length = frameNodesCount;
  4566. for (var i = 0; i < frameNodesCount; i++) {
  4567. var node = frameNodes.getNodeByIndex(i);
  4568. var property = this._avatar ? this._avatarNodeMap[this._avatar._rootNode.name] : this.owner;
  4569. for (var j = 0, m = node.ownerPathCount; j < m; j++) {
  4570. var ownPat = node.getOwnerPathByIndex(j);
  4571. if (ownPat === "") {
  4572. break;
  4573. }
  4574. else {
  4575. property = property.getChildByName(ownPat);
  4576. if (!property)
  4577. break;
  4578. }
  4579. }
  4580. if (property) {
  4581. var propertyOwner = node.propertyOwner;
  4582. (propertyOwner) && (property = property[propertyOwner]);
  4583. property && this._addKeyframeNodeOwner(nodeOwners, node, property);
  4584. }
  4585. }
  4586. }
  4587. _updatePlayer(animatorState, playState, elapsedTime, islooping) {
  4588. var clipDuration = animatorState._clip._duration * (animatorState.clipEnd - animatorState.clipStart);
  4589. var lastElapsedTime = playState._elapsedTime;
  4590. var elapsedPlaybackTime = lastElapsedTime + elapsedTime;
  4591. playState._lastElapsedTime = lastElapsedTime;
  4592. playState._elapsedTime = elapsedPlaybackTime;
  4593. var normalizedTime = elapsedPlaybackTime / clipDuration;
  4594. playState._normalizedTime = normalizedTime;
  4595. var playTime = normalizedTime % 1.0;
  4596. playState._normalizedPlayTime = playTime < 0 ? playTime + 1.0 : playTime;
  4597. playState._duration = clipDuration;
  4598. var scripts = animatorState._scripts;
  4599. if ((!islooping && elapsedPlaybackTime >= clipDuration)) {
  4600. playState._finish = true;
  4601. playState._elapsedTime = clipDuration;
  4602. playState._normalizedPlayTime = 1.0;
  4603. if (scripts) {
  4604. for (var i = 0, n = scripts.length; i < n; i++)
  4605. scripts[i].onStateExit();
  4606. }
  4607. return;
  4608. }
  4609. if (scripts) {
  4610. for (i = 0, n = scripts.length; i < n; i++)
  4611. scripts[i].onStateUpdate();
  4612. }
  4613. }
  4614. _eventScript(scripts, events, eventIndex, endTime, front) {
  4615. if (front) {
  4616. for (var n = events.length; eventIndex < n; eventIndex++) {
  4617. var event = events[eventIndex];
  4618. if (event.time <= endTime) {
  4619. for (var j = 0, m = scripts.length; j < m; j++) {
  4620. var script = scripts[j];
  4621. var fun = script[event.eventName];
  4622. (fun) && (fun.apply(script, event.params));
  4623. }
  4624. }
  4625. else {
  4626. break;
  4627. }
  4628. }
  4629. }
  4630. else {
  4631. for (; eventIndex >= 0; eventIndex--) {
  4632. event = events[eventIndex];
  4633. if (event.time >= endTime) {
  4634. for (j = 0, m = scripts.length; j < m; j++) {
  4635. script = scripts[j];
  4636. fun = script[event.eventName];
  4637. (fun) && (fun.apply(script, event.params));
  4638. }
  4639. }
  4640. else {
  4641. break;
  4642. }
  4643. }
  4644. }
  4645. return eventIndex;
  4646. }
  4647. _updateEventScript(stateInfo, playStateInfo) {
  4648. var scripts = this.owner._scripts;
  4649. if (scripts) {
  4650. var clip = stateInfo._clip;
  4651. var events = clip._animationEvents;
  4652. var clipDuration = clip._duration;
  4653. var elapsedTime = playStateInfo._elapsedTime;
  4654. var time = elapsedTime % clipDuration;
  4655. var loopCount = Math.abs(Math.floor(elapsedTime / clipDuration) - Math.floor(playStateInfo._lastElapsedTime / clipDuration));
  4656. var frontPlay = playStateInfo._elapsedTime >= playStateInfo._lastElapsedTime;
  4657. if (playStateInfo._lastIsFront !== frontPlay) {
  4658. if (frontPlay)
  4659. playStateInfo._playEventIndex++;
  4660. else
  4661. playStateInfo._playEventIndex--;
  4662. playStateInfo._lastIsFront = frontPlay;
  4663. }
  4664. if (loopCount == 0) {
  4665. playStateInfo._playEventIndex = this._eventScript(scripts, events, playStateInfo._playEventIndex, time, frontPlay);
  4666. }
  4667. else {
  4668. if (frontPlay) {
  4669. this._eventScript(scripts, events, playStateInfo._playEventIndex, clipDuration, true);
  4670. for (var i = 0, n = loopCount - 1; i < n; i++)
  4671. this._eventScript(scripts, events, 0, clipDuration, true);
  4672. playStateInfo._playEventIndex = this._eventScript(scripts, events, 0, time, true);
  4673. }
  4674. else {
  4675. this._eventScript(scripts, events, playStateInfo._playEventIndex, 0, false);
  4676. var eventIndex = events.length - 1;
  4677. for (i = 0, n = loopCount - 1; i < n; i++)
  4678. this._eventScript(scripts, events, eventIndex, 0, false);
  4679. playStateInfo._playEventIndex = this._eventScript(scripts, events, eventIndex, time, false);
  4680. }
  4681. }
  4682. }
  4683. }
  4684. _updateClipDatas(animatorState, addtive, playStateInfo, scale) {
  4685. var clip = animatorState._clip;
  4686. var clipDuration = clip._duration;
  4687. var curPlayTime = animatorState.clipStart * clipDuration + playStateInfo._normalizedPlayTime * playStateInfo._duration;
  4688. var currentFrameIndices = animatorState._currentFrameIndices;
  4689. var frontPlay = playStateInfo._elapsedTime > playStateInfo._lastElapsedTime;
  4690. clip._evaluateClipDatasRealTime(clip._nodes, curPlayTime, currentFrameIndices, addtive, frontPlay);
  4691. }
  4692. _applyFloat(pro, proName, nodeOwner, additive, weight, isFirstLayer, data) {
  4693. if (nodeOwner.updateMark === this._updateMark) {
  4694. if (additive) {
  4695. pro[proName] += weight * (data);
  4696. }
  4697. else {
  4698. var oriValue = pro[proName];
  4699. pro[proName] = oriValue + weight * (data - oriValue);
  4700. }
  4701. }
  4702. else {
  4703. if (isFirstLayer) {
  4704. if (additive)
  4705. pro[proName] = nodeOwner.defaultValue + data;
  4706. else
  4707. pro[proName] = data;
  4708. }
  4709. else {
  4710. if (additive) {
  4711. pro[proName] = nodeOwner.defaultValue + weight * (data);
  4712. }
  4713. else {
  4714. var defValue = nodeOwner.defaultValue;
  4715. pro[proName] = defValue + weight * (data - defValue);
  4716. }
  4717. }
  4718. }
  4719. }
  4720. _applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, data, out) {
  4721. if (nodeOwner.updateMark === this._updateMark) {
  4722. if (additive) {
  4723. out.x += weight * data.x;
  4724. out.y += weight * data.y;
  4725. out.z += weight * data.z;
  4726. }
  4727. else {
  4728. var oriX = out.x;
  4729. var oriY = out.y;
  4730. var oriZ = out.z;
  4731. out.x = oriX + weight * (data.x - oriX);
  4732. out.y = oriY + weight * (data.y - oriY);
  4733. out.z = oriZ + weight * (data.z - oriZ);
  4734. }
  4735. }
  4736. else {
  4737. if (isFirstLayer) {
  4738. if (additive) {
  4739. var defValue = nodeOwner.defaultValue;
  4740. out.x = defValue.x + data.x;
  4741. out.y = defValue.y + data.y;
  4742. out.z = defValue.z + data.z;
  4743. }
  4744. else {
  4745. out.x = data.x;
  4746. out.y = data.y;
  4747. out.z = data.z;
  4748. }
  4749. }
  4750. else {
  4751. defValue = nodeOwner.defaultValue;
  4752. if (additive) {
  4753. out.x = defValue.x + weight * data.x;
  4754. out.y = defValue.y + weight * data.y;
  4755. out.z = defValue.z + weight * data.z;
  4756. }
  4757. else {
  4758. var defX = defValue.x;
  4759. var defY = defValue.y;
  4760. var defZ = defValue.z;
  4761. out.x = defX + weight * (data.x - defX);
  4762. out.y = defY + weight * (data.y - defY);
  4763. out.z = defZ + weight * (data.z - defZ);
  4764. }
  4765. }
  4766. }
  4767. }
  4768. _applyRotation(nodeOwner, additive, weight, isFirstLayer, clipRot, localRotation) {
  4769. if (nodeOwner.updateMark === this._updateMark) {
  4770. if (additive) {
  4771. var tempQuat = Animator._tempQuaternion1;
  4772. Utils3D.quaternionWeight(clipRot, weight, tempQuat);
  4773. tempQuat.normalize(tempQuat);
  4774. Quaternion.multiply(localRotation, tempQuat, localRotation);
  4775. }
  4776. else {
  4777. Quaternion.lerp(localRotation, clipRot, weight, localRotation);
  4778. }
  4779. }
  4780. else {
  4781. if (isFirstLayer) {
  4782. if (additive) {
  4783. var defaultRot = nodeOwner.defaultValue;
  4784. Quaternion.multiply(defaultRot, clipRot, localRotation);
  4785. }
  4786. else {
  4787. localRotation.x = clipRot.x;
  4788. localRotation.y = clipRot.y;
  4789. localRotation.z = clipRot.z;
  4790. localRotation.w = clipRot.w;
  4791. }
  4792. }
  4793. else {
  4794. defaultRot = nodeOwner.defaultValue;
  4795. if (additive) {
  4796. tempQuat = Animator._tempQuaternion1;
  4797. Utils3D.quaternionWeight(clipRot, weight, tempQuat);
  4798. tempQuat.normalize(tempQuat);
  4799. Quaternion.multiply(defaultRot, tempQuat, localRotation);
  4800. }
  4801. else {
  4802. Quaternion.lerp(defaultRot, clipRot, weight, localRotation);
  4803. }
  4804. }
  4805. }
  4806. }
  4807. _applyScale(nodeOwner, additive, weight, isFirstLayer, clipSca, localScale) {
  4808. if (nodeOwner.updateMark === this._updateMark) {
  4809. if (additive) {
  4810. var scale = Animator._tempVector31;
  4811. Utils3D.scaleWeight(clipSca, weight, scale);
  4812. localScale.x = localScale.x * scale.x;
  4813. localScale.y = localScale.y * scale.y;
  4814. localScale.z = localScale.z * scale.z;
  4815. }
  4816. else {
  4817. Utils3D.scaleBlend(localScale, clipSca, weight, localScale);
  4818. }
  4819. }
  4820. else {
  4821. if (isFirstLayer) {
  4822. if (additive) {
  4823. var defaultSca = nodeOwner.defaultValue;
  4824. localScale.x = defaultSca.x * clipSca.x;
  4825. localScale.y = defaultSca.y * clipSca.y;
  4826. localScale.z = defaultSca.z * clipSca.z;
  4827. }
  4828. else {
  4829. localScale.x = clipSca.x;
  4830. localScale.y = clipSca.y;
  4831. localScale.z = clipSca.z;
  4832. }
  4833. }
  4834. else {
  4835. defaultSca = nodeOwner.defaultValue;
  4836. if (additive) {
  4837. scale = Animator._tempVector31;
  4838. Utils3D.scaleWeight(clipSca, weight, scale);
  4839. localScale.x = defaultSca.x * scale.x;
  4840. localScale.y = defaultSca.y * scale.y;
  4841. localScale.z = defaultSca.z * scale.z;
  4842. }
  4843. else {
  4844. Utils3D.scaleBlend(defaultSca, clipSca, weight, localScale);
  4845. }
  4846. }
  4847. }
  4848. }
  4849. _applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight) {
  4850. var pro = nodeOwner.propertyOwner;
  4851. if (pro) {
  4852. switch (nodeOwner.type) {
  4853. case 0:
  4854. var proPat = nodeOwner.property;
  4855. var m = proPat.length - 1;
  4856. for (var j = 0; j < m; j++) {
  4857. pro = pro[proPat[j]];
  4858. if (!pro)
  4859. break;
  4860. }
  4861. var crossValue = srcValue + crossWeight * (desValue - srcValue);
  4862. this._applyFloat(pro, proPat[m], nodeOwner, additive, weight, isFirstLayer, crossValue);
  4863. break;
  4864. case 1:
  4865. var localPos = pro.localPosition;
  4866. var position = Animator._tempVector30;
  4867. var srcX = srcValue.x, srcY = srcValue.y, srcZ = srcValue.z;
  4868. position.x = srcX + crossWeight * (desValue.x - srcX);
  4869. position.y = srcY + crossWeight * (desValue.y - srcY);
  4870. position.z = srcZ + crossWeight * (desValue.z - srcZ);
  4871. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, position, localPos);
  4872. pro.localPosition = localPos;
  4873. break;
  4874. case 2:
  4875. var localRot = pro.localRotation;
  4876. var rotation = Animator._tempQuaternion0;
  4877. Quaternion.lerp(srcValue, desValue, crossWeight, rotation);
  4878. this._applyRotation(nodeOwner, additive, weight, isFirstLayer, rotation, localRot);
  4879. pro.localRotation = localRot;
  4880. break;
  4881. case 3:
  4882. var localSca = pro.localScale;
  4883. var scale = Animator._tempVector30;
  4884. Utils3D.scaleBlend(srcValue, desValue, crossWeight, scale);
  4885. this._applyScale(nodeOwner, additive, weight, isFirstLayer, scale, localSca);
  4886. pro.localScale = localSca;
  4887. break;
  4888. case 4:
  4889. var localEuler = pro.localRotationEuler;
  4890. var rotationEuler = Animator._tempVector30;
  4891. srcX = srcValue.x, srcY = srcValue.y, srcZ = srcValue.z;
  4892. rotationEuler.x = srcX + crossWeight * (desValue.x - srcX);
  4893. rotationEuler.y = srcY + crossWeight * (desValue.y - srcY);
  4894. rotationEuler.z = srcZ + crossWeight * (desValue.z - srcZ);
  4895. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, rotationEuler, localEuler);
  4896. pro.localRotationEuler = localEuler;
  4897. break;
  4898. }
  4899. nodeOwner.updateMark = this._updateMark;
  4900. }
  4901. }
  4902. _setClipDatasToNode(stateInfo, additive, weight, isFirstLayer) {
  4903. var nodes = stateInfo._clip._nodes;
  4904. var nodeOwners = stateInfo._nodeOwners;
  4905. for (var i = 0, n = nodes.count; i < n; i++) {
  4906. var nodeOwner = nodeOwners[i];
  4907. if (nodeOwner) {
  4908. var pro = nodeOwner.propertyOwner;
  4909. if (pro) {
  4910. switch (nodeOwner.type) {
  4911. case 0:
  4912. var proPat = nodeOwner.property;
  4913. var m = proPat.length - 1;
  4914. for (var j = 0; j < m; j++) {
  4915. pro = pro[proPat[j]];
  4916. if (!pro)
  4917. break;
  4918. }
  4919. this._applyFloat(pro, proPat[m], nodeOwner, additive, weight, isFirstLayer, nodes.getNodeByIndex(i).data);
  4920. break;
  4921. case 1:
  4922. var localPos = pro.localPosition;
  4923. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, nodes.getNodeByIndex(i).data, localPos);
  4924. pro.localPosition = localPos;
  4925. break;
  4926. case 2:
  4927. var localRot = pro.localRotation;
  4928. this._applyRotation(nodeOwner, additive, weight, isFirstLayer, nodes.getNodeByIndex(i).data, localRot);
  4929. pro.localRotation = localRot;
  4930. break;
  4931. case 3:
  4932. var localSca = pro.localScale;
  4933. this._applyScale(nodeOwner, additive, weight, isFirstLayer, nodes.getNodeByIndex(i).data, localSca);
  4934. pro.localScale = localSca;
  4935. break;
  4936. case 4:
  4937. var localEuler = pro.localRotationEuler;
  4938. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, nodes.getNodeByIndex(i).data, localEuler);
  4939. pro.localRotationEuler = localEuler;
  4940. break;
  4941. }
  4942. nodeOwner.updateMark = this._updateMark;
  4943. }
  4944. }
  4945. }
  4946. }
  4947. _setCrossClipDatasToNode(controllerLayer, srcState, destState, crossWeight, isFirstLayer) {
  4948. var nodeOwners = controllerLayer._crossNodesOwners;
  4949. var ownerCount = controllerLayer._crossNodesOwnersCount;
  4950. var additive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  4951. var weight = controllerLayer.defaultWeight;
  4952. var destDataIndices = controllerLayer._destCrossClipNodeIndices;
  4953. var destNodes = destState._clip._nodes;
  4954. var destNodeOwners = destState._nodeOwners;
  4955. var srcDataIndices = controllerLayer._srcCrossClipNodeIndices;
  4956. var srcNodeOwners = srcState._nodeOwners;
  4957. var srcNodes = srcState._clip._nodes;
  4958. for (var i = 0; i < ownerCount; i++) {
  4959. var nodeOwner = nodeOwners[i];
  4960. if (nodeOwner) {
  4961. var srcIndex = srcDataIndices[i];
  4962. var destIndex = destDataIndices[i];
  4963. var srcValue = srcIndex !== -1 ? srcNodes.getNodeByIndex(srcIndex).data : destNodeOwners[destIndex].defaultValue;
  4964. var desValue = destIndex !== -1 ? destNodes.getNodeByIndex(destIndex).data : srcNodeOwners[srcIndex].defaultValue;
  4965. this._applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight);
  4966. }
  4967. }
  4968. }
  4969. _setFixedCrossClipDatasToNode(controllerLayer, destState, crossWeight, isFirstLayer) {
  4970. var nodeOwners = controllerLayer._crossNodesOwners;
  4971. var ownerCount = controllerLayer._crossNodesOwnersCount;
  4972. var additive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  4973. var weight = controllerLayer.defaultWeight;
  4974. var destDataIndices = controllerLayer._destCrossClipNodeIndices;
  4975. var destNodes = destState._clip._nodes;
  4976. for (var i = 0; i < ownerCount; i++) {
  4977. var nodeOwner = nodeOwners[i];
  4978. if (nodeOwner) {
  4979. var destIndex = destDataIndices[i];
  4980. var srcValue = nodeOwner.crossFixedValue;
  4981. var desValue = destIndex !== -1 ? destNodes.getNodeByIndex(destIndex).data : nodeOwner.defaultValue;
  4982. this._applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight);
  4983. }
  4984. }
  4985. }
  4986. _revertDefaultKeyframeNodes(clipStateInfo) {
  4987. var nodeOwners = clipStateInfo._nodeOwners;
  4988. for (var i = 0, n = nodeOwners.length; i < n; i++) {
  4989. var nodeOwner = nodeOwners[i];
  4990. if (nodeOwner) {
  4991. var pro = nodeOwner.propertyOwner;
  4992. if (pro) {
  4993. switch (nodeOwner.type) {
  4994. case 0:
  4995. var proPat = nodeOwner.property;
  4996. var m = proPat.length - 1;
  4997. for (var j = 0; j < m; j++) {
  4998. pro = pro[proPat[j]];
  4999. if (!pro)
  5000. break;
  5001. }
  5002. pro[proPat[m]] = nodeOwner.defaultValue;
  5003. break;
  5004. case 1:
  5005. var locPos = pro.localPosition;
  5006. var def = nodeOwner.defaultValue;
  5007. locPos.x = def.x;
  5008. locPos.y = def.y;
  5009. locPos.z = def.z;
  5010. pro.localPosition = locPos;
  5011. break;
  5012. case 2:
  5013. var locRot = pro.localRotation;
  5014. var defQua = nodeOwner.defaultValue;
  5015. locRot.x = defQua.x;
  5016. locRot.y = defQua.y;
  5017. locRot.z = defQua.z;
  5018. locRot.w = defQua.w;
  5019. pro.localRotation = locRot;
  5020. break;
  5021. case 3:
  5022. var locSca = pro.localScale;
  5023. def = nodeOwner.defaultValue;
  5024. locSca.x = def.x;
  5025. locSca.y = def.y;
  5026. locSca.z = def.z;
  5027. pro.localScale = locSca;
  5028. break;
  5029. case 4:
  5030. var locEul = pro.localRotationEuler;
  5031. def = nodeOwner.defaultValue;
  5032. locEul.x = def.x;
  5033. locEul.y = def.y;
  5034. locEul.z = def.z;
  5035. pro.localRotationEuler = locEul;
  5036. break;
  5037. default:
  5038. throw "Animator:unknown type.";
  5039. }
  5040. }
  5041. }
  5042. }
  5043. }
  5044. _onAdded() {
  5045. var parent = this.owner._parent;
  5046. this.owner._setHierarchyAnimator(this, parent ? parent._hierarchyAnimator : null);
  5047. this.owner._changeAnimatorToLinkSprite3DNoAvatar(this, true, []);
  5048. }
  5049. _onDestroy() {
  5050. for (var i = 0, n = this._controllerLayers.length; i < n; i++)
  5051. this._controllerLayers[i]._removeReference();
  5052. var parent = this.owner._parent;
  5053. this.owner._clearHierarchyAnimator(this, parent ? parent._hierarchyAnimator : null);
  5054. }
  5055. _onEnable() {
  5056. this.owner._scene._animatorPool.add(this);
  5057. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  5058. if (this._controllerLayers[i].playOnWake) {
  5059. var defaultClip = this.getDefaultState(i);
  5060. (defaultClip) && (this.play(null, i, 0));
  5061. }
  5062. }
  5063. }
  5064. _onDisable() {
  5065. this.owner._scene._animatorPool.remove(this);
  5066. }
  5067. _handleSpriteOwnersBySprite(isLink, path, sprite) {
  5068. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  5069. var clipStateInfos = this._controllerLayers[i]._states;
  5070. for (var j = 0, m = clipStateInfos.length; j < m; j++) {
  5071. var clipStateInfo = clipStateInfos[j];
  5072. var clip = clipStateInfo._clip;
  5073. var nodePath = path.join("/");
  5074. var ownersNodes = clip._nodesMap[nodePath];
  5075. if (ownersNodes) {
  5076. var nodeOwners = clipStateInfo._nodeOwners;
  5077. for (var k = 0, p = ownersNodes.length; k < p; k++) {
  5078. if (isLink)
  5079. this._addKeyframeNodeOwner(nodeOwners, ownersNodes[k], sprite);
  5080. else
  5081. this._removeKeyframeNodeOwner(nodeOwners, ownersNodes[k]);
  5082. }
  5083. }
  5084. }
  5085. }
  5086. }
  5087. _parse(data) {
  5088. var avatarData = data.avatar;
  5089. if (avatarData) {
  5090. this.avatar = Laya.Loader.getRes(avatarData.path);
  5091. var linkSprites = avatarData.linkSprites;
  5092. this._linkSprites = linkSprites;
  5093. this._linkToSprites(linkSprites);
  5094. }
  5095. var clipPaths = data.clipPaths;
  5096. var play = data.playOnWake;
  5097. var layersData = data.layers;
  5098. for (var i = 0; i < layersData.length; i++) {
  5099. var layerData = layersData[i];
  5100. var animatorLayer = new AnimatorControllerLayer(layerData.name);
  5101. if (i === 0)
  5102. animatorLayer.defaultWeight = 1.0;
  5103. else
  5104. animatorLayer.defaultWeight = layerData.weight;
  5105. var blendingModeData = layerData.blendingMode;
  5106. (blendingModeData) && (animatorLayer.blendingMode = blendingModeData);
  5107. this.addControllerLayer(animatorLayer);
  5108. var states = layerData.states;
  5109. for (var j = 0, m = states.length; j < m; j++) {
  5110. var state = states[j];
  5111. var clipPath = state.clipPath;
  5112. if (clipPath) {
  5113. var name = state.name;
  5114. var motion;
  5115. motion = Laya.Loader.getRes(clipPath);
  5116. if (motion) {
  5117. var animatorState = new AnimatorState();
  5118. animatorState.name = name;
  5119. animatorState.clip = motion;
  5120. animatorLayer.addState(animatorState);
  5121. (j === 0) && (this.getControllerLayer(i).defaultState = animatorState);
  5122. }
  5123. }
  5124. }
  5125. (play !== undefined) && (animatorLayer.playOnWake = play);
  5126. }
  5127. var cullingModeData = data.cullingMode;
  5128. (cullingModeData !== undefined) && (this.cullingMode = cullingModeData);
  5129. }
  5130. _update() {
  5131. var timer = this.owner._scene.timer;
  5132. var delta = timer._delta / 1000.0;
  5133. if (this._speed === 0 || delta === 0)
  5134. return;
  5135. var needRender;
  5136. if (this.cullingMode === Animator.CULLINGMODE_CULLCOMPLETELY) {
  5137. needRender = false;
  5138. for (var i = 0, n = this._renderableSprites.length; i < n; i++) {
  5139. if (this._renderableSprites[i]._render._visible) {
  5140. needRender = true;
  5141. break;
  5142. }
  5143. }
  5144. }
  5145. else {
  5146. needRender = true;
  5147. }
  5148. this._updateMark++;
  5149. var timerScale = timer.scale;
  5150. for (i = 0, n = this._controllerLayers.length; i < n; i++) {
  5151. var controllerLayer = this._controllerLayers[i];
  5152. var playStateInfo = controllerLayer._playStateInfo;
  5153. var crossPlayStateInfo = controllerLayer._crossPlayStateInfo;
  5154. addtive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  5155. switch (controllerLayer._playType) {
  5156. case 0:
  5157. var animatorState = controllerLayer._currentPlayState;
  5158. var clip = animatorState._clip;
  5159. var speed = this._speed * animatorState.speed;
  5160. var finish = playStateInfo._finish;
  5161. finish || this._updatePlayer(animatorState, playStateInfo, delta * speed, clip.islooping);
  5162. if (needRender) {
  5163. var addtive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  5164. this._updateClipDatas(animatorState, addtive, playStateInfo, timerScale * speed);
  5165. this._setClipDatasToNode(animatorState, addtive, controllerLayer.defaultWeight, i === 0);
  5166. finish || this._updateEventScript(animatorState, playStateInfo);
  5167. }
  5168. break;
  5169. case 1:
  5170. animatorState = controllerLayer._currentPlayState;
  5171. clip = animatorState._clip;
  5172. var crossClipState = controllerLayer._crossPlayState;
  5173. var crossClip = crossClipState._clip;
  5174. var crossDuratuion = controllerLayer._crossDuration;
  5175. var startPlayTime = crossPlayStateInfo._startPlayTime;
  5176. var crossClipDuration = crossClip._duration - startPlayTime;
  5177. var crossScale = crossDuratuion > crossClipDuration ? crossClipDuration / crossDuratuion : 1.0;
  5178. var crossSpeed = this._speed * crossClipState.speed;
  5179. this._updatePlayer(crossClipState, crossPlayStateInfo, delta * crossScale * crossSpeed, crossClip.islooping);
  5180. var crossWeight = ((crossPlayStateInfo._elapsedTime - startPlayTime) / crossScale) / crossDuratuion;
  5181. if (crossWeight >= 1.0) {
  5182. if (needRender) {
  5183. this._updateClipDatas(crossClipState, addtive, crossPlayStateInfo, timerScale * crossSpeed);
  5184. this._setClipDatasToNode(crossClipState, addtive, controllerLayer.defaultWeight, i === 0);
  5185. controllerLayer._playType = 0;
  5186. controllerLayer._currentPlayState = crossClipState;
  5187. crossPlayStateInfo._cloneTo(playStateInfo);
  5188. }
  5189. }
  5190. else {
  5191. if (!playStateInfo._finish) {
  5192. speed = this._speed * animatorState.speed;
  5193. this._updatePlayer(animatorState, playStateInfo, delta * speed, clip.islooping);
  5194. }
  5195. if (needRender) {
  5196. this._updateClipDatas(animatorState, addtive, playStateInfo, timerScale * speed);
  5197. this._updateClipDatas(crossClipState, addtive, crossPlayStateInfo, timerScale * crossScale * crossSpeed);
  5198. this._setCrossClipDatasToNode(controllerLayer, animatorState, crossClipState, crossWeight, i === 0);
  5199. }
  5200. }
  5201. if (needRender) {
  5202. this._updateEventScript(animatorState, playStateInfo);
  5203. this._updateEventScript(crossClipState, crossPlayStateInfo);
  5204. }
  5205. break;
  5206. case 2:
  5207. crossClipState = controllerLayer._crossPlayState;
  5208. crossClip = crossClipState._clip;
  5209. crossDuratuion = controllerLayer._crossDuration;
  5210. startPlayTime = crossPlayStateInfo._startPlayTime;
  5211. crossClipDuration = crossClip._duration - startPlayTime;
  5212. crossScale = crossDuratuion > crossClipDuration ? crossClipDuration / crossDuratuion : 1.0;
  5213. crossSpeed = this._speed * crossClipState.speed;
  5214. this._updatePlayer(crossClipState, crossPlayStateInfo, delta * crossScale * crossSpeed, crossClip.islooping);
  5215. if (needRender) {
  5216. crossWeight = ((crossPlayStateInfo._elapsedTime - startPlayTime) / crossScale) / crossDuratuion;
  5217. if (crossWeight >= 1.0) {
  5218. this._updateClipDatas(crossClipState, addtive, crossPlayStateInfo, timerScale * crossSpeed);
  5219. this._setClipDatasToNode(crossClipState, addtive, 1.0, i === 0);
  5220. controllerLayer._playType = 0;
  5221. controllerLayer._currentPlayState = crossClipState;
  5222. crossPlayStateInfo._cloneTo(playStateInfo);
  5223. }
  5224. else {
  5225. this._updateClipDatas(crossClipState, addtive, crossPlayStateInfo, timerScale * crossScale * crossSpeed);
  5226. this._setFixedCrossClipDatasToNode(controllerLayer, crossClipState, crossWeight, i === 0);
  5227. }
  5228. this._updateEventScript(crossClipState, crossPlayStateInfo);
  5229. }
  5230. break;
  5231. }
  5232. }
  5233. if (needRender) {
  5234. if (this._avatar) {
  5235. Laya.Render.supportWebGLPlusAnimation && this._updateAnimationNodeWorldMatix(this._animationNodeLocalPositions, this._animationNodeLocalRotations, this._animationNodeLocalScales, this._animationNodeWorldMatrixs, this._animationNodeParentIndices);
  5236. this._updateAvatarNodesToSprite();
  5237. }
  5238. }
  5239. }
  5240. _cloneTo(dest) {
  5241. var animator = dest;
  5242. animator.avatar = this.avatar;
  5243. animator.cullingMode = this.cullingMode;
  5244. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  5245. var controllLayer = this._controllerLayers[i];
  5246. animator.addControllerLayer(controllLayer.clone());
  5247. var animatorStates = controllLayer._states;
  5248. for (var j = 0, m = animatorStates.length; j < m; j++) {
  5249. var state = animatorStates[j].clone();
  5250. var cloneLayer = animator.getControllerLayer(i);
  5251. cloneLayer.addState(state);
  5252. (j == 0) && (cloneLayer.defaultState = state);
  5253. }
  5254. }
  5255. animator._linkSprites = this._linkSprites;
  5256. animator._linkToSprites(this._linkSprites);
  5257. }
  5258. getDefaultState(layerIndex = 0) {
  5259. var controllerLayer = this._controllerLayers[layerIndex];
  5260. return controllerLayer.defaultState;
  5261. }
  5262. addState(state, layerIndex = 0) {
  5263. var controllerLayer = this._controllerLayers[layerIndex];
  5264. controllerLayer.addState(state);
  5265. console.warn("Animator:this function is discard,please use animatorControllerLayer.addState() instead.");
  5266. }
  5267. removeState(state, layerIndex = 0) {
  5268. var controllerLayer = this._controllerLayers[layerIndex];
  5269. controllerLayer.removeState(state);
  5270. console.warn("Animator:this function is discard,please use animatorControllerLayer.removeState() instead.");
  5271. }
  5272. addControllerLayer(controllderLayer) {
  5273. this._controllerLayers.push(controllderLayer);
  5274. controllderLayer._animator = this;
  5275. controllderLayer._addReference();
  5276. var states = controllderLayer._states;
  5277. for (var i = 0, n = states.length; i < n; i++)
  5278. this._getOwnersByClip(states[i]);
  5279. }
  5280. getControllerLayer(layerInex = 0) {
  5281. return this._controllerLayers[layerInex];
  5282. }
  5283. getCurrentAnimatorPlayState(layerInex = 0) {
  5284. return this._controllerLayers[layerInex]._playStateInfo;
  5285. }
  5286. play(name = null, layerIndex = 0, normalizedTime = Number.NEGATIVE_INFINITY) {
  5287. var controllerLayer = this._controllerLayers[layerIndex];
  5288. if (controllerLayer) {
  5289. var defaultState = controllerLayer.defaultState;
  5290. if (!name && !defaultState)
  5291. throw new Error("Animator:must have default clip value,please set clip property.");
  5292. var curPlayState = controllerLayer._currentPlayState;
  5293. var playStateInfo = controllerLayer._playStateInfo;
  5294. var animatorState = name ? controllerLayer._statesMap[name] : defaultState;
  5295. var clipDuration = animatorState._clip._duration;
  5296. if (curPlayState !== animatorState) {
  5297. if (normalizedTime !== Number.NEGATIVE_INFINITY)
  5298. playStateInfo._resetPlayState(clipDuration * normalizedTime);
  5299. else
  5300. playStateInfo._resetPlayState(0.0);
  5301. (curPlayState !== null && curPlayState !== animatorState) && (this._revertDefaultKeyframeNodes(curPlayState));
  5302. controllerLayer._playType = 0;
  5303. controllerLayer._currentPlayState = animatorState;
  5304. }
  5305. else {
  5306. if (normalizedTime !== Number.NEGATIVE_INFINITY) {
  5307. playStateInfo._resetPlayState(clipDuration * normalizedTime);
  5308. controllerLayer._playType = 0;
  5309. }
  5310. }
  5311. var scripts = animatorState._scripts;
  5312. if (scripts) {
  5313. for (var i = 0, n = scripts.length; i < n; i++)
  5314. scripts[i].onStateEnter();
  5315. }
  5316. }
  5317. else {
  5318. console.warn("Invalid layerIndex " + layerIndex + ".");
  5319. }
  5320. }
  5321. crossFade(name, transitionDuration, layerIndex = 0, normalizedTime = Number.NEGATIVE_INFINITY) {
  5322. var controllerLayer = this._controllerLayers[layerIndex];
  5323. if (controllerLayer) {
  5324. var destAnimatorState = controllerLayer._statesMap[name];
  5325. if (destAnimatorState) {
  5326. var playType = controllerLayer._playType;
  5327. if (playType === -1) {
  5328. this.play(name, layerIndex, normalizedTime);
  5329. return;
  5330. }
  5331. var crossPlayStateInfo = controllerLayer._crossPlayStateInfo;
  5332. var crossNodeOwners = controllerLayer._crossNodesOwners;
  5333. var crossNodeOwnerIndicesMap = controllerLayer._crossNodesOwnersIndicesMap;
  5334. var srcAnimatorState = controllerLayer._currentPlayState;
  5335. var destNodeOwners = destAnimatorState._nodeOwners;
  5336. var destCrossClipNodeIndices = controllerLayer._destCrossClipNodeIndices;
  5337. var destClip = destAnimatorState._clip;
  5338. var destNodes = destClip._nodes;
  5339. var destNodesMap = destClip._nodesDic;
  5340. switch (playType) {
  5341. case 0:
  5342. var srcNodeOwners = srcAnimatorState._nodeOwners;
  5343. var scrCrossClipNodeIndices = controllerLayer._srcCrossClipNodeIndices;
  5344. var srcClip = srcAnimatorState._clip;
  5345. var srcNodes = srcClip._nodes;
  5346. var srcNodesMap = srcClip._nodesDic;
  5347. controllerLayer._playType = 1;
  5348. var crossMark = ++controllerLayer._crossMark;
  5349. var crossCount = controllerLayer._crossNodesOwnersCount = 0;
  5350. for (var i = 0, n = srcNodes.count; i < n; i++) {
  5351. var srcNode = srcNodes.getNodeByIndex(i);
  5352. var srcIndex = srcNode._indexInList;
  5353. var srcNodeOwner = srcNodeOwners[srcIndex];
  5354. if (srcNodeOwner) {
  5355. var srcFullPath = srcNode.fullPath;
  5356. scrCrossClipNodeIndices[crossCount] = srcIndex;
  5357. var destNode = destNodesMap[srcFullPath];
  5358. if (destNode)
  5359. destCrossClipNodeIndices[crossCount] = destNode._indexInList;
  5360. else
  5361. destCrossClipNodeIndices[crossCount] = -1;
  5362. crossNodeOwnerIndicesMap[srcFullPath] = crossMark;
  5363. crossNodeOwners[crossCount] = srcNodeOwner;
  5364. crossCount++;
  5365. }
  5366. }
  5367. for (i = 0, n = destNodes.count; i < n; i++) {
  5368. destNode = destNodes.getNodeByIndex(i);
  5369. var destIndex = destNode._indexInList;
  5370. var destNodeOwner = destNodeOwners[destIndex];
  5371. if (destNodeOwner) {
  5372. var destFullPath = destNode.fullPath;
  5373. if (!srcNodesMap[destFullPath]) {
  5374. scrCrossClipNodeIndices[crossCount] = -1;
  5375. destCrossClipNodeIndices[crossCount] = destIndex;
  5376. crossNodeOwnerIndicesMap[destFullPath] = crossMark;
  5377. crossNodeOwners[crossCount] = destNodeOwner;
  5378. crossCount++;
  5379. }
  5380. }
  5381. }
  5382. break;
  5383. case 1:
  5384. case 2:
  5385. controllerLayer._playType = 2;
  5386. for (i = 0, n = crossNodeOwners.length; i < n; i++) {
  5387. var nodeOwner = crossNodeOwners[i];
  5388. nodeOwner.saveCrossFixedValue();
  5389. destNode = destNodesMap[nodeOwner.fullPath];
  5390. if (destNode)
  5391. destCrossClipNodeIndices[i] = destNode._indexInList;
  5392. else
  5393. destCrossClipNodeIndices[i] = -1;
  5394. }
  5395. crossCount = controllerLayer._crossNodesOwnersCount;
  5396. crossMark = controllerLayer._crossMark;
  5397. for (i = 0, n = destNodes.count; i < n; i++) {
  5398. destNode = destNodes.getNodeByIndex(i);
  5399. destIndex = destNode._indexInList;
  5400. destNodeOwner = destNodeOwners[destIndex];
  5401. if (destNodeOwner) {
  5402. destFullPath = destNode.fullPath;
  5403. if (crossNodeOwnerIndicesMap[destFullPath] !== crossMark) {
  5404. destCrossClipNodeIndices[crossCount] = destIndex;
  5405. crossNodeOwnerIndicesMap[destFullPath] = crossMark;
  5406. nodeOwner = destNodeOwners[destIndex];
  5407. crossNodeOwners[crossCount] = nodeOwner;
  5408. nodeOwner.saveCrossFixedValue();
  5409. crossCount++;
  5410. }
  5411. }
  5412. }
  5413. break;
  5414. default:
  5415. }
  5416. controllerLayer._crossNodesOwnersCount = crossCount;
  5417. controllerLayer._crossPlayState = destAnimatorState;
  5418. controllerLayer._crossDuration = srcAnimatorState._clip._duration * transitionDuration;
  5419. if (normalizedTime !== Number.NEGATIVE_INFINITY)
  5420. crossPlayStateInfo._resetPlayState(destClip._duration * normalizedTime);
  5421. else
  5422. crossPlayStateInfo._resetPlayState(0.0);
  5423. var scripts = destAnimatorState._scripts;
  5424. if (scripts) {
  5425. for (i = 0, n = scripts.length; i < n; i++)
  5426. scripts[i].onStateEnter();
  5427. }
  5428. }
  5429. else {
  5430. console.warn("Invalid name " + layerIndex + ".");
  5431. }
  5432. }
  5433. else {
  5434. console.warn("Invalid layerIndex " + layerIndex + ".");
  5435. }
  5436. }
  5437. get avatar() {
  5438. return this._avatar;
  5439. }
  5440. set avatar(value) {
  5441. if (this._avatar !== value) {
  5442. this._avatar = value;
  5443. if (value) {
  5444. this._getAvatarOwnersAndInitDatasAsync();
  5445. this.owner._changeHierarchyAnimatorAvatar(this, value);
  5446. }
  5447. else {
  5448. var parent = this.owner._parent;
  5449. this.owner._changeHierarchyAnimatorAvatar(this, parent ? parent._hierarchyAnimator._avatar : null);
  5450. }
  5451. }
  5452. }
  5453. _getAvatarOwnersAndInitDatasAsync() {
  5454. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  5455. var clipStateInfos = this._controllerLayers[i]._states;
  5456. for (var j = 0, m = clipStateInfos.length; j < m; j++)
  5457. this._getOwnersByClip(clipStateInfos[j]);
  5458. }
  5459. this._avatar._cloneDatasToAnimator(this);
  5460. for (var k in this._linkAvatarSpritesData) {
  5461. var sprites = this._linkAvatarSpritesData[k];
  5462. if (sprites) {
  5463. for (var c = 0, p = sprites.length; c < p; c++)
  5464. this._isLinkSpriteToAnimationNode(sprites[c], k, true);
  5465. }
  5466. }
  5467. }
  5468. _isLinkSpriteToAnimationNode(sprite, nodeName, isLink) {
  5469. if (this._avatar) {
  5470. var node = this._avatarNodeMap[nodeName];
  5471. if (node) {
  5472. if (isLink) {
  5473. sprite._transform._dummy = node.transform;
  5474. this._linkAvatarSprites.push(sprite);
  5475. var nodeTransform = node.transform;
  5476. var spriteTransform = sprite.transform;
  5477. if (!spriteTransform.owner.isStatic && nodeTransform) {
  5478. var spriteWorldMatrix = spriteTransform.worldMatrix;
  5479. var ownParTra = this.owner._transform._parent;
  5480. if (ownParTra) {
  5481. Utils3D.matrix4x4MultiplyMFM(ownParTra.worldMatrix, nodeTransform.getWorldMatrix(), spriteWorldMatrix);
  5482. }
  5483. else {
  5484. var sprWorE = spriteWorldMatrix.elements;
  5485. var nodWorE = nodeTransform.getWorldMatrix();
  5486. for (var i = 0; i < 16; i++)
  5487. sprWorE[i] = nodWorE[i];
  5488. }
  5489. spriteTransform.worldMatrix = spriteWorldMatrix;
  5490. }
  5491. }
  5492. else {
  5493. sprite._transform._dummy = null;
  5494. this._linkAvatarSprites.splice(this._linkAvatarSprites.indexOf(sprite), 1);
  5495. }
  5496. }
  5497. }
  5498. }
  5499. _isLinkSpriteToAnimationNodeData(sprite, nodeName, isLink) {
  5500. var linkSprites = this._linkAvatarSpritesData[nodeName];
  5501. if (isLink) {
  5502. linkSprites || (this._linkAvatarSpritesData[nodeName] = linkSprites = []);
  5503. linkSprites.push(sprite);
  5504. }
  5505. else {
  5506. var index = linkSprites.indexOf(sprite);
  5507. linkSprites.splice(index, 1);
  5508. }
  5509. }
  5510. _updateAvatarNodesToSprite() {
  5511. for (var i = 0, n = this._linkAvatarSprites.length; i < n; i++) {
  5512. var sprite = this._linkAvatarSprites[i];
  5513. var nodeTransform = sprite.transform._dummy;
  5514. var spriteTransform = sprite.transform;
  5515. if (!spriteTransform.owner.isStatic && nodeTransform) {
  5516. var spriteWorldMatrix = spriteTransform.worldMatrix;
  5517. var ownTra = this.owner._transform;
  5518. Utils3D.matrix4x4MultiplyMFM(ownTra.worldMatrix, nodeTransform.getWorldMatrix(), spriteWorldMatrix);
  5519. spriteTransform.worldMatrix = spriteWorldMatrix;
  5520. }
  5521. }
  5522. }
  5523. linkSprite3DToAvatarNode(nodeName, sprite3D) {
  5524. this._isLinkSpriteToAnimationNodeData(sprite3D, nodeName, true);
  5525. this._isLinkSpriteToAnimationNode(sprite3D, nodeName, true);
  5526. return true;
  5527. }
  5528. unLinkSprite3DToAvatarNode(sprite3D) {
  5529. if (sprite3D._hierarchyAnimator === this) {
  5530. var dummy = sprite3D.transform._dummy;
  5531. if (dummy) {
  5532. var nodeName = dummy._owner.name;
  5533. this._isLinkSpriteToAnimationNodeData(sprite3D, nodeName, false);
  5534. this._isLinkSpriteToAnimationNode(sprite3D, nodeName, false);
  5535. return true;
  5536. }
  5537. else {
  5538. return false;
  5539. }
  5540. }
  5541. else {
  5542. throw ("Animator:sprite3D must belong to this Animator");
  5543. return false;
  5544. }
  5545. }
  5546. _updateAnimationNodeWorldMatix(localPositions, localRotations, localScales, worldMatrixs, parentIndices) {
  5547. Laya.LayaGL.instance.updateAnimationNodeWorldMatix(localPositions, localRotations, localScales, parentIndices, worldMatrixs);
  5548. }
  5549. }
  5550. Animator._tempVector30 = new Vector3();
  5551. Animator._tempVector31 = new Vector3();
  5552. Animator._tempQuaternion0 = new Quaternion();
  5553. Animator._tempQuaternion1 = new Quaternion();
  5554. Animator.CULLINGMODE_ALWAYSANIMATE = 0;
  5555. Animator.CULLINGMODE_CULLCOMPLETELY = 2;
  5556. class PostProcessRenderContext {
  5557. constructor() {
  5558. this.source = null;
  5559. this.destination = null;
  5560. this.camera = null;
  5561. this.compositeShaderData = null;
  5562. this.command = null;
  5563. this.deferredReleaseTextures = [];
  5564. }
  5565. }
  5566. class RenderContext3D {
  5567. constructor() {
  5568. }
  5569. }
  5570. RenderContext3D._instance = new RenderContext3D();
  5571. class RenderTexture extends Laya.BaseTexture {
  5572. constructor(width, height, format = Laya.RenderTextureFormat.R8G8B8, depthStencilFormat = Laya.RenderTextureDepthFormat.DEPTH_16) {
  5573. super(format, false);
  5574. this._inPool = false;
  5575. this._glTextureType = Laya.LayaGL.instance.TEXTURE_2D;
  5576. this._width = width;
  5577. this._height = height;
  5578. this._depthStencilFormat = depthStencilFormat;
  5579. this._create(width, height);
  5580. }
  5581. static get currentActive() {
  5582. return RenderTexture._currentActive;
  5583. }
  5584. static createFromPool(width, height, format = Laya.RenderTextureFormat.R8G8B8, depthStencilFormat = Laya.RenderTextureDepthFormat.DEPTH_16, filterMode = Laya.BaseTexture.FILTERMODE_BILINEAR) {
  5585. var tex;
  5586. for (var i = 0, n = RenderTexture._pool.length; i < n; i++) {
  5587. tex = RenderTexture._pool[i];
  5588. if (tex._width == width && tex._height == height && tex._format == format && tex._depthStencilFormat == depthStencilFormat && tex._filterMode == filterMode) {
  5589. tex._inPool = false;
  5590. var end = RenderTexture._pool[n - 1];
  5591. RenderTexture._pool[i] = end;
  5592. RenderTexture._pool.length -= 1;
  5593. return tex;
  5594. }
  5595. }
  5596. tex = new RenderTexture(width, height, format, depthStencilFormat);
  5597. tex.filterMode = filterMode;
  5598. tex.lock = true;
  5599. return tex;
  5600. }
  5601. static recoverToPool(renderTexture) {
  5602. if (renderTexture._inPool)
  5603. return;
  5604. RenderTexture._pool.push(renderTexture);
  5605. renderTexture._inPool = true;
  5606. }
  5607. get depthStencilFormat() {
  5608. return this._depthStencilFormat;
  5609. }
  5610. get defaulteTexture() {
  5611. return Laya.Texture2D.grayTexture;
  5612. }
  5613. _texImage2D(gl, glTextureType, width, height) {
  5614. switch (this._format) {
  5615. case Laya.RenderTextureFormat.R8G8B8:
  5616. gl.texImage2D(glTextureType, 0, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, null);
  5617. break;
  5618. case Laya.RenderTextureFormat.R8G8B8A8:
  5619. gl.texImage2D(glTextureType, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  5620. break;
  5621. case Laya.RenderTextureFormat.Alpha8:
  5622. gl.texImage2D(glTextureType, 0, gl.ALPHA, width, height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, null);
  5623. break;
  5624. case Laya.RenderTextureFormat.R16G16B16A16:
  5625. if (Laya.LayaGL.layaGPUInstance._isWebGL2)
  5626. gl.texImage2D(this._glTextureType, 0, gl.RGBA16F, width, height, 0, gl.RGBA, gl.HALF_FLOAT, null);
  5627. else
  5628. gl.texImage2D(this._glTextureType, 0, gl.RGBA, width, height, 0, gl.RGBA, Laya.LayaGL.layaGPUInstance._oesTextureHalfFloat.HALF_FLOAT_OES, null);
  5629. break;
  5630. default:
  5631. break;
  5632. }
  5633. }
  5634. _create(width, height) {
  5635. var gl = Laya.LayaGL.instance;
  5636. this._frameBuffer = gl.createFramebuffer();
  5637. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  5638. this._texImage2D(gl, this._glTextureType, width, height);
  5639. this._setGPUMemory(width * height * 4);
  5640. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  5641. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._glTexture, 0);
  5642. if (this._depthStencilFormat !== Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE) {
  5643. this._depthStencilBuffer = gl.createRenderbuffer();
  5644. gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthStencilBuffer);
  5645. switch (this._depthStencilFormat) {
  5646. case Laya.RenderTextureDepthFormat.DEPTH_16:
  5647. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5648. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  5649. break;
  5650. case Laya.RenderTextureDepthFormat.STENCIL_8:
  5651. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, width, height);
  5652. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  5653. break;
  5654. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_16_8:
  5655. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  5656. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  5657. break;
  5658. default:
  5659. throw "RenderTexture: unkonw depth format.";
  5660. }
  5661. }
  5662. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5663. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5664. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  5665. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  5666. this._setFilterMode(this._filterMode);
  5667. this._setAnisotropy(this._anisoLevel);
  5668. this._readyed = true;
  5669. this._activeResource();
  5670. }
  5671. _start() {
  5672. var gl = Laya.LayaGL.instance;
  5673. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  5674. RenderTexture._currentActive = this;
  5675. this._readyed = false;
  5676. }
  5677. _end() {
  5678. var gl = Laya.LayaGL.instance;
  5679. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5680. RenderTexture._currentActive = null;
  5681. this._readyed = true;
  5682. }
  5683. getData(x, y, width, height, out) {
  5684. if (Laya.Render.isConchApp && window.conchConfig.threadMode == 2) {
  5685. throw "native 2 thread mode use getDataAsync";
  5686. }
  5687. var gl = Laya.LayaGL.instance;
  5688. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  5689. var canRead = (gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE);
  5690. if (!canRead) {
  5691. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5692. return null;
  5693. }
  5694. gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, out);
  5695. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5696. return out;
  5697. }
  5698. getDataAsync(x, y, width, height, callBack) {
  5699. var gl = Laya.LayaGL.instance;
  5700. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  5701. gl.readPixelsAsync(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, function (data) {
  5702. callBack(new Uint8Array(data));
  5703. });
  5704. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5705. }
  5706. _disposeResource() {
  5707. if (this._frameBuffer) {
  5708. var gl = Laya.LayaGL.instance;
  5709. gl.deleteTexture(this._glTexture);
  5710. gl.deleteFramebuffer(this._frameBuffer);
  5711. gl.deleteRenderbuffer(this._depthStencilBuffer);
  5712. this._glTexture = null;
  5713. this._frameBuffer = null;
  5714. this._depthStencilBuffer = null;
  5715. this._setGPUMemory(0);
  5716. }
  5717. }
  5718. }
  5719. RenderTexture._pool = [];
  5720. class DefineDatas {
  5721. constructor() {
  5722. this._mask = [];
  5723. this._length = 0;
  5724. }
  5725. _intersectionDefineDatas(define) {
  5726. var unionMask = define._mask;
  5727. var mask = this._mask;
  5728. for (var i = this._length - 1; i >= 0; i--) {
  5729. var value = mask[i] & unionMask[i];
  5730. if (value == 0 && i == this._length - 1)
  5731. this._length--;
  5732. else
  5733. mask[i] = value;
  5734. }
  5735. }
  5736. add(define) {
  5737. var index = define._index;
  5738. var size = index + 1;
  5739. var mask = this._mask;
  5740. var maskStart = mask.length;
  5741. if (maskStart < size) {
  5742. mask.length = size;
  5743. for (; maskStart < index; maskStart++)
  5744. mask[maskStart] = 0;
  5745. mask[index] = define._value;
  5746. this._length = size;
  5747. }
  5748. else {
  5749. if (size > this._length) {
  5750. mask[index] = define._value;
  5751. this._length = size;
  5752. }
  5753. else {
  5754. mask[index] |= define._value;
  5755. }
  5756. }
  5757. }
  5758. remove(define) {
  5759. var index = define._index;
  5760. var mask = this._mask;
  5761. var endIndex = this._length - 1;
  5762. if (index > endIndex)
  5763. return;
  5764. var newValue = mask[index] & ~define._value;
  5765. if (index == endIndex && newValue === 0)
  5766. this._length--;
  5767. else
  5768. mask[index] = newValue;
  5769. }
  5770. addDefineDatas(define) {
  5771. var addMask = define._mask;
  5772. var size = define._length;
  5773. var mask = this._mask;
  5774. var maskStart = mask.length;
  5775. if (maskStart < size) {
  5776. mask.length = size;
  5777. for (var i = 0; i < maskStart; i++)
  5778. mask[i] |= addMask[i];
  5779. for (; maskStart < size; maskStart++)
  5780. mask[maskStart] = addMask[maskStart];
  5781. this._length = size;
  5782. }
  5783. else {
  5784. for (var i = 0; i < size; i++)
  5785. mask[i] |= addMask[i];
  5786. this._length = Math.max(this._length, size);
  5787. }
  5788. }
  5789. removeDefineDatas(define) {
  5790. var removeMask = define._mask;
  5791. var mask = this._mask;
  5792. var endIndex = this._length - 1;
  5793. for (var i = define._length - 1; i >= 0; i--) {
  5794. if (i > endIndex)
  5795. continue;
  5796. var newValue = mask[i] & ~removeMask[i];
  5797. if (i == endIndex && newValue === 0) {
  5798. endIndex--;
  5799. this._length--;
  5800. }
  5801. else {
  5802. mask[i] = newValue;
  5803. }
  5804. }
  5805. }
  5806. has(define) {
  5807. var index = define._index;
  5808. if (index >= this._length)
  5809. return false;
  5810. return (this._mask[index] & define._value) !== 0;
  5811. }
  5812. clear() {
  5813. this._length = 0;
  5814. }
  5815. cloneTo(destObject) {
  5816. var destDefineData = destObject;
  5817. var destMask = destDefineData._mask;
  5818. var mask = this._mask;
  5819. var count = this._length;
  5820. destMask.length = count;
  5821. for (var i = 0; i < count; i++)
  5822. destMask[i] = mask[i];
  5823. destDefineData._length = count;
  5824. }
  5825. clone() {
  5826. var dest = new DefineDatas();
  5827. this.cloneTo(dest);
  5828. return dest;
  5829. }
  5830. }
  5831. class ShaderDefine {
  5832. constructor(index, value) {
  5833. this._index = index;
  5834. this._value = value;
  5835. }
  5836. }
  5837. class Shader3D {
  5838. constructor(name, attributeMap, uniformMap, enableInstancing) {
  5839. this._attributeMap = null;
  5840. this._uniformMap = null;
  5841. this._enableInstancing = false;
  5842. this._subShaders = [];
  5843. this._name = name;
  5844. this._attributeMap = attributeMap;
  5845. this._uniformMap = uniformMap;
  5846. this._enableInstancing = enableInstancing;
  5847. }
  5848. static _getNamesByDefineData(defineData, out) {
  5849. var maskMap = Shader3D._maskMap;
  5850. var mask = defineData._mask;
  5851. out.length = 0;
  5852. for (var i = 0, n = defineData._length; i < n; i++) {
  5853. var subMaskMap = maskMap[i];
  5854. var subMask = mask[i];
  5855. for (var j = 0; j < 32; j++) {
  5856. var d = 1 << j;
  5857. if (subMask > 0 && d > subMask)
  5858. break;
  5859. if (subMask & d)
  5860. out.push(subMaskMap[d]);
  5861. }
  5862. }
  5863. }
  5864. static getDefineByName(name) {
  5865. var define = Shader3D._defineMap[name];
  5866. if (!define) {
  5867. var maskMap = Shader3D._maskMap;
  5868. var counter = Shader3D._defineCounter;
  5869. var index = Math.floor(counter / 32);
  5870. var value = 1 << counter % 32;
  5871. define = new ShaderDefine(index, value);
  5872. Shader3D._defineMap[name] = define;
  5873. if (index == maskMap.length) {
  5874. maskMap.length++;
  5875. maskMap[index] = {};
  5876. }
  5877. maskMap[index][value] = name;
  5878. Shader3D._defineCounter++;
  5879. }
  5880. return define;
  5881. }
  5882. static propertyNameToID(name) {
  5883. if (Shader3D._propertyNameMap[name] != null) {
  5884. return Shader3D._propertyNameMap[name];
  5885. }
  5886. else {
  5887. var id = Shader3D._propertyNameCounter++;
  5888. Shader3D._propertyNameMap[name] = id;
  5889. return id;
  5890. }
  5891. }
  5892. static addInclude(fileName, txt) {
  5893. txt = txt.replace(Laya.ShaderCompile._clearCR, "");
  5894. Laya.ShaderCompile.addInclude(fileName, txt);
  5895. }
  5896. static compileShaderByDefineNames(shaderName, subShaderIndex, passIndex, defineNames) {
  5897. var shader = Shader3D.find(shaderName);
  5898. if (shader) {
  5899. var subShader = shader.getSubShaderAt(subShaderIndex);
  5900. if (subShader) {
  5901. var pass = subShader._passes[passIndex];
  5902. if (pass) {
  5903. var compileDefineDatas = Shader3D._compileDefineDatas;
  5904. compileDefineDatas.clear();
  5905. for (var i = 0, n = defineNames.length; i < n; i++)
  5906. compileDefineDatas.add(Shader3D.getDefineByName(defineNames[i]));
  5907. (Laya.WebGL.shaderHighPrecision) && (compileDefineDatas.add(Shader3D.SHADERDEFINE_HIGHPRECISION));
  5908. (Config3D._config._multiLighting) || (compileDefineDatas.add(Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING));
  5909. pass.withCompile(compileDefineDatas);
  5910. }
  5911. else {
  5912. console.warn("Shader3D: unknown passIndex.");
  5913. }
  5914. }
  5915. else {
  5916. console.warn("Shader3D: unknown subShaderIndex.");
  5917. }
  5918. }
  5919. else {
  5920. console.warn("Shader3D: unknown shader name.");
  5921. }
  5922. }
  5923. static compileShader(shaderName, subShaderIndex, passIndex, ...defineMask) {
  5924. var shader = Shader3D.find(shaderName);
  5925. if (shader) {
  5926. var subShader = shader.getSubShaderAt(subShaderIndex);
  5927. if (subShader) {
  5928. var pass = subShader._passes[passIndex];
  5929. if (pass) {
  5930. var compileDefineDatas = Shader3D._compileDefineDatas;
  5931. var mask = compileDefineDatas._mask;
  5932. mask.length = 0;
  5933. for (var i = 0, n = defineMask.length; i < n; i++)
  5934. mask.push(defineMask[i]);
  5935. compileDefineDatas._length = defineMask.length;
  5936. (Laya.WebGL.shaderHighPrecision) && (compileDefineDatas.add(Shader3D.SHADERDEFINE_HIGHPRECISION));
  5937. (Config3D._config._multiLighting) || (compileDefineDatas.add(Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING));
  5938. pass.withCompile(compileDefineDatas);
  5939. }
  5940. else {
  5941. console.warn("Shader3D: unknown passIndex.");
  5942. }
  5943. }
  5944. else {
  5945. console.warn("Shader3D: unknown subShaderIndex.");
  5946. }
  5947. }
  5948. else {
  5949. console.warn("Shader3D: unknown shader name.");
  5950. }
  5951. }
  5952. static add(name, attributeMap = null, uniformMap = null, enableInstancing = false) {
  5953. return Shader3D._preCompileShader[name] = new Shader3D(name, attributeMap, uniformMap, enableInstancing);
  5954. }
  5955. static find(name) {
  5956. return Shader3D._preCompileShader[name];
  5957. }
  5958. addSubShader(subShader) {
  5959. this._subShaders.push(subShader);
  5960. subShader._owner = this;
  5961. }
  5962. getSubShaderAt(index) {
  5963. return this._subShaders[index];
  5964. }
  5965. }
  5966. Shader3D._compileDefineDatas = new DefineDatas();
  5967. Shader3D.RENDER_STATE_CULL = 0;
  5968. Shader3D.RENDER_STATE_BLEND = 1;
  5969. Shader3D.RENDER_STATE_BLEND_SRC = 2;
  5970. Shader3D.RENDER_STATE_BLEND_DST = 3;
  5971. Shader3D.RENDER_STATE_BLEND_SRC_RGB = 4;
  5972. Shader3D.RENDER_STATE_BLEND_DST_RGB = 5;
  5973. Shader3D.RENDER_STATE_BLEND_SRC_ALPHA = 6;
  5974. Shader3D.RENDER_STATE_BLEND_DST_ALPHA = 7;
  5975. Shader3D.RENDER_STATE_BLEND_CONST_COLOR = 8;
  5976. Shader3D.RENDER_STATE_BLEND_EQUATION = 9;
  5977. Shader3D.RENDER_STATE_BLEND_EQUATION_RGB = 10;
  5978. Shader3D.RENDER_STATE_BLEND_EQUATION_ALPHA = 11;
  5979. Shader3D.RENDER_STATE_DEPTH_TEST = 12;
  5980. Shader3D.RENDER_STATE_DEPTH_WRITE = 13;
  5981. Shader3D.PERIOD_CUSTOM = 0;
  5982. Shader3D.PERIOD_MATERIAL = 1;
  5983. Shader3D.PERIOD_SPRITE = 2;
  5984. Shader3D.PERIOD_CAMERA = 3;
  5985. Shader3D.PERIOD_SCENE = 4;
  5986. Shader3D._propertyNameCounter = 0;
  5987. Shader3D._propertyNameMap = {};
  5988. Shader3D._defineCounter = 0;
  5989. Shader3D._defineMap = {};
  5990. Shader3D._preCompileShader = {};
  5991. Shader3D._maskMap = [];
  5992. Shader3D.debugMode = true;
  5993. class ShaderData {
  5994. constructor(ownerResource = null) {
  5995. this._ownerResource = null;
  5996. this._data = null;
  5997. this._defineDatas = new DefineDatas();
  5998. this._runtimeCopyValues = [];
  5999. this._ownerResource = ownerResource;
  6000. this._initData();
  6001. }
  6002. _initData() {
  6003. this._data = new Object();
  6004. }
  6005. getData() {
  6006. return this._data;
  6007. }
  6008. addDefine(define) {
  6009. this._defineDatas.add(define);
  6010. }
  6011. removeDefine(define) {
  6012. this._defineDatas.remove(define);
  6013. }
  6014. hasDefine(define) {
  6015. return this._defineDatas.has(define);
  6016. }
  6017. clearDefine() {
  6018. this._defineDatas.clear();
  6019. }
  6020. getBool(index) {
  6021. return this._data[index];
  6022. }
  6023. setBool(index, value) {
  6024. this._data[index] = value;
  6025. }
  6026. getInt(index) {
  6027. return this._data[index];
  6028. }
  6029. setInt(index, value) {
  6030. this._data[index] = value;
  6031. }
  6032. getNumber(index) {
  6033. return this._data[index];
  6034. }
  6035. setNumber(index, value) {
  6036. this._data[index] = value;
  6037. }
  6038. getVector2(index) {
  6039. return this._data[index];
  6040. }
  6041. setVector2(index, value) {
  6042. this._data[index] = value;
  6043. }
  6044. getVector3(index) {
  6045. return this._data[index];
  6046. }
  6047. setVector3(index, value) {
  6048. this._data[index] = value;
  6049. }
  6050. getVector(index) {
  6051. return this._data[index];
  6052. }
  6053. setVector(index, value) {
  6054. this._data[index] = value;
  6055. }
  6056. getQuaternion(index) {
  6057. return this._data[index];
  6058. }
  6059. setQuaternion(index, value) {
  6060. this._data[index] = value;
  6061. }
  6062. getMatrix4x4(index) {
  6063. return this._data[index];
  6064. }
  6065. setMatrix4x4(index, value) {
  6066. this._data[index] = value;
  6067. }
  6068. getBuffer(shaderIndex) {
  6069. return this._data[shaderIndex];
  6070. }
  6071. setBuffer(index, value) {
  6072. this._data[index] = value;
  6073. }
  6074. setTexture(index, value) {
  6075. var lastValue = this._data[index];
  6076. this._data[index] = value;
  6077. if (this._ownerResource && this._ownerResource.referenceCount > 0) {
  6078. (lastValue) && (lastValue._removeReference());
  6079. (value) && (value._addReference());
  6080. }
  6081. }
  6082. getTexture(index) {
  6083. return this._data[index];
  6084. }
  6085. setAttribute(index, value) {
  6086. this._data[index] = value;
  6087. }
  6088. getAttribute(index) {
  6089. return this._data[index];
  6090. }
  6091. getLength() {
  6092. return this._data.length;
  6093. }
  6094. setLength(value) {
  6095. this._data.length = value;
  6096. }
  6097. cloneTo(destObject) {
  6098. var dest = destObject;
  6099. var destData = dest._data;
  6100. for (var k in this._data) {
  6101. var value = this._data[k];
  6102. if (value != null) {
  6103. if (typeof (value) == 'number') {
  6104. destData[k] = value;
  6105. }
  6106. else if (typeof (value) == 'number') {
  6107. destData[k] = value;
  6108. }
  6109. else if (typeof (value) == "boolean") {
  6110. destData[k] = value;
  6111. }
  6112. else if (value instanceof Vector2) {
  6113. var v2 = (destData[k]) || (destData[k] = new Vector2());
  6114. value.cloneTo(v2);
  6115. destData[k] = v2;
  6116. }
  6117. else if (value instanceof Vector3) {
  6118. var v3 = (destData[k]) || (destData[k] = new Vector3());
  6119. value.cloneTo(v3);
  6120. destData[k] = v3;
  6121. }
  6122. else if (value instanceof Vector4) {
  6123. var v4 = (destData[k]) || (destData[k] = new Vector4());
  6124. value.cloneTo(v4);
  6125. destData[k] = v4;
  6126. }
  6127. else if (value instanceof Matrix4x4) {
  6128. var mat = (destData[k]) || (destData[k] = new Matrix4x4());
  6129. value.cloneTo(mat);
  6130. destData[k] = mat;
  6131. }
  6132. else if (value instanceof Laya.BaseTexture) {
  6133. destData[k] = value;
  6134. }
  6135. }
  6136. }
  6137. this._defineDatas.cloneTo(dest._defineDatas);
  6138. }
  6139. clone() {
  6140. var dest = new ShaderData();
  6141. this.cloneTo(dest);
  6142. return dest;
  6143. }
  6144. cloneToForNative(destObject) {
  6145. var dest = destObject;
  6146. var diffSize = this._int32Data.length - dest._int32Data.length;
  6147. if (diffSize > 0) {
  6148. dest.needRenewArrayBufferForNative(this._int32Data.length);
  6149. }
  6150. dest._int32Data.set(this._int32Data, 0);
  6151. var destData = dest._nativeArray;
  6152. var dataCount = this._nativeArray.length;
  6153. destData.length = dataCount;
  6154. for (var i = 0; i < dataCount; i++) {
  6155. var value = this._nativeArray[i];
  6156. if (value) {
  6157. if (typeof (value) == 'number') {
  6158. destData[i] = value;
  6159. dest.setNumber(i, value);
  6160. }
  6161. else if (typeof (value) == 'number') {
  6162. destData[i] = value;
  6163. dest.setInt(i, value);
  6164. }
  6165. else if (typeof (value) == "boolean") {
  6166. destData[i] = value;
  6167. dest.setBool(i, value);
  6168. }
  6169. else if (value instanceof Vector2) {
  6170. var v2 = (destData[i]) || (destData[i] = new Vector2());
  6171. value.cloneTo(v2);
  6172. destData[i] = v2;
  6173. dest.setVector2(i, v2);
  6174. }
  6175. else if (value instanceof Vector3) {
  6176. var v3 = (destData[i]) || (destData[i] = new Vector3());
  6177. value.cloneTo(v3);
  6178. destData[i] = v3;
  6179. dest.setVector3(i, v3);
  6180. }
  6181. else if (value instanceof Vector4) {
  6182. var v4 = (destData[i]) || (destData[i] = new Vector4());
  6183. value.cloneTo(v4);
  6184. destData[i] = v4;
  6185. dest.setVector(i, v4);
  6186. }
  6187. else if (value instanceof Matrix4x4) {
  6188. var mat = (destData[i]) || (destData[i] = new Matrix4x4());
  6189. value.cloneTo(mat);
  6190. destData[i] = mat;
  6191. dest.setMatrix4x4(i, mat);
  6192. }
  6193. else if (value instanceof Laya.BaseTexture) {
  6194. destData[i] = value;
  6195. dest.setTexture(i, value);
  6196. }
  6197. }
  6198. }
  6199. this._defineDatas.cloneTo(dest._defineDatas);
  6200. }
  6201. _initDataForNative() {
  6202. var length = 8;
  6203. this._frameCount = -1;
  6204. this._runtimeCopyValues.length = 0;
  6205. this._nativeArray = [];
  6206. this._data = new ArrayBuffer(length * 4);
  6207. this._int32Data = new Int32Array(this._data);
  6208. this._float32Data = new Float32Array(this._data);
  6209. Laya.LayaGL.instance.createArrayBufferRef(this._data, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true);
  6210. }
  6211. needRenewArrayBufferForNative(index) {
  6212. if (index >= this._int32Data.length) {
  6213. var nByteLen = (index + 1) * 4;
  6214. var pre = this._int32Data;
  6215. var preConchRef = this._data["conchRef"];
  6216. var prePtrID = this._data["_ptrID"];
  6217. this._data = new ArrayBuffer(nByteLen);
  6218. this._int32Data = new Int32Array(this._data);
  6219. this._float32Data = new Float32Array(this._data);
  6220. this._data["conchRef"] = preConchRef;
  6221. this._data["_ptrID"] = prePtrID;
  6222. pre && this._int32Data.set(pre, 0);
  6223. var layagl = Laya.LayaGL.instance;
  6224. if (layagl.updateArrayBufferRef) {
  6225. layagl.updateArrayBufferRef(this._data['_ptrID'], preConchRef.isSyncToRender(), this._data);
  6226. }
  6227. else {
  6228. window.conch.updateArrayBufferRef(this._data['_ptrID'], preConchRef.isSyncToRender(), this._data);
  6229. }
  6230. }
  6231. }
  6232. getDataForNative() {
  6233. return this._nativeArray;
  6234. }
  6235. getIntForNative(index) {
  6236. return this._int32Data[index];
  6237. }
  6238. setIntForNative(index, value) {
  6239. this.needRenewArrayBufferForNative(index);
  6240. this._int32Data[index] = value;
  6241. this._nativeArray[index] = value;
  6242. }
  6243. getBoolForNative(index) {
  6244. return this._int32Data[index] == 1;
  6245. }
  6246. setBoolForNative(index, value) {
  6247. this.needRenewArrayBufferForNative(index);
  6248. this._int32Data[index] = value ? 1 : 0;
  6249. this._nativeArray[index] = value;
  6250. }
  6251. getNumberForNative(index) {
  6252. return this._float32Data[index];
  6253. }
  6254. setNumberForNative(index, value) {
  6255. this.needRenewArrayBufferForNative(index);
  6256. this._float32Data[index] = value;
  6257. this._nativeArray[index] = value;
  6258. }
  6259. getMatrix4x4ForNative(index) {
  6260. return this._nativeArray[index];
  6261. }
  6262. setMatrix4x4ForNative(index, value) {
  6263. this.needRenewArrayBufferForNative(index);
  6264. this._nativeArray[index] = value;
  6265. var nPtrID = this.setReferenceForNative(value.elements);
  6266. this._int32Data[index] = nPtrID;
  6267. }
  6268. getVectorForNative(index) {
  6269. return this._nativeArray[index];
  6270. }
  6271. setVectorForNative(index, value) {
  6272. this.needRenewArrayBufferForNative(index);
  6273. this._nativeArray[index] = value;
  6274. if (!value.elements) {
  6275. value.forNativeElement();
  6276. }
  6277. var nPtrID = this.setReferenceForNative(value.elements);
  6278. this._int32Data[index] = nPtrID;
  6279. }
  6280. getVector2ForNative(index) {
  6281. return this._nativeArray[index];
  6282. }
  6283. setVector2ForNative(index, value) {
  6284. this.needRenewArrayBufferForNative(index);
  6285. this._nativeArray[index] = value;
  6286. if (!value.elements) {
  6287. value.forNativeElement();
  6288. }
  6289. var nPtrID = this.setReferenceForNative(value.elements);
  6290. this._int32Data[index] = nPtrID;
  6291. }
  6292. getVector3ForNative(index) {
  6293. return this._nativeArray[index];
  6294. }
  6295. setVector3ForNative(index, value) {
  6296. this.needRenewArrayBufferForNative(index);
  6297. this._nativeArray[index] = value;
  6298. if (!value.elements) {
  6299. value.forNativeElement();
  6300. }
  6301. var nPtrID = this.setReferenceForNative(value.elements);
  6302. this._int32Data[index] = nPtrID;
  6303. }
  6304. getQuaternionForNative(index) {
  6305. return this._nativeArray[index];
  6306. }
  6307. setQuaternionForNative(index, value) {
  6308. this.needRenewArrayBufferForNative(index);
  6309. this._nativeArray[index] = value;
  6310. if (!value.elements) {
  6311. value.forNativeElement();
  6312. }
  6313. var nPtrID = this.setReferenceForNative(value.elements);
  6314. this._int32Data[index] = nPtrID;
  6315. }
  6316. getBufferForNative(shaderIndex) {
  6317. return this._nativeArray[shaderIndex];
  6318. }
  6319. setBufferForNative(index, value) {
  6320. this.needRenewArrayBufferForNative(index);
  6321. this._nativeArray[index] = value;
  6322. var nPtrID = this.setReferenceForNative(value);
  6323. this._int32Data[index] = nPtrID;
  6324. }
  6325. getAttributeForNative(index) {
  6326. return this._nativeArray[index];
  6327. }
  6328. setAttributeForNative(index, value) {
  6329. this._nativeArray[index] = value;
  6330. if (!value["_ptrID"]) {
  6331. Laya.LayaGL.instance.createArrayBufferRef(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true);
  6332. }
  6333. Laya.LayaGL.instance.syncBufferToRenderThread(value);
  6334. this._int32Data[index] = value["_ptrID"];
  6335. }
  6336. getTextureForNative(index) {
  6337. return this._nativeArray[index];
  6338. }
  6339. setTextureForNative(index, value) {
  6340. if (!value)
  6341. return;
  6342. this.needRenewArrayBufferForNative(index);
  6343. var lastValue = this._nativeArray[index];
  6344. this._nativeArray[index] = value;
  6345. var glTexture = value._getSource() || value.defaulteTexture._getSource();
  6346. this._int32Data[index] = glTexture.id;
  6347. if (this._ownerResource && this._ownerResource.referenceCount > 0) {
  6348. (lastValue) && (lastValue._removeReference());
  6349. (value) && (value._addReference());
  6350. }
  6351. }
  6352. setReferenceForNative(value) {
  6353. this.clearRuntimeCopyArray();
  6354. var nRefID = 0;
  6355. var nPtrID = 0;
  6356. if (ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_) {
  6357. Laya.LayaGL.instance.createArrayBufferRefs(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true, Laya.LayaGL.ARRAY_BUFFER_REF_REFERENCE);
  6358. nRefID = 0;
  6359. nPtrID = value.getPtrID(nRefID);
  6360. }
  6361. else {
  6362. Laya.LayaGL.instance.createArrayBufferRefs(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true, Laya.LayaGL.ARRAY_BUFFER_REF_COPY);
  6363. nRefID = value.getRefNum() - 1;
  6364. nPtrID = value.getPtrID(nRefID);
  6365. this._runtimeCopyValues.push({ "obj": value, "refID": nRefID, "ptrID": nPtrID });
  6366. }
  6367. Laya.LayaGL.instance.syncBufferToRenderThread(value, nRefID);
  6368. return nPtrID;
  6369. }
  6370. static setRuntimeValueMode(bReference) {
  6371. ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_ = bReference;
  6372. }
  6373. clearRuntimeCopyArray() {
  6374. var currentFrame = Laya.Stat.loopCount;
  6375. if (this._frameCount != currentFrame) {
  6376. this._frameCount = currentFrame;
  6377. for (var i = 0, n = this._runtimeCopyValues.length; i < n; i++) {
  6378. var obj = this._runtimeCopyValues[i];
  6379. obj.obj.clearRefNum();
  6380. }
  6381. this._runtimeCopyValues.length = 0;
  6382. }
  6383. }
  6384. }
  6385. ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_ = true;
  6386. class PostProcess {
  6387. constructor() {
  6388. this._compositeShader = Shader3D.find("PostProcessComposite");
  6389. this._compositeShaderData = new ShaderData();
  6390. this._context = null;
  6391. this._effects = [];
  6392. this._context = new PostProcessRenderContext();
  6393. this._context.compositeShaderData = this._compositeShaderData;
  6394. }
  6395. static __init__() {
  6396. PostProcess.SHADERDEFINE_BLOOM_LOW = Shader3D.getDefineByName("BLOOM_LOW");
  6397. PostProcess.SHADERDEFINE_BLOOM = Shader3D.getDefineByName("BLOOM");
  6398. PostProcess.SHADERDEFINE_FINALPASS = Shader3D.getDefineByName("FINALPASS");
  6399. }
  6400. _init(camera, command) {
  6401. this._context.camera = camera;
  6402. this._context.command = command;
  6403. }
  6404. _render() {
  6405. var noteValue = ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_;
  6406. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(false);
  6407. var camera = this._context.camera;
  6408. var screenTexture = RenderTexture.createFromPool(RenderContext3D.clientWidth, RenderContext3D.clientHeight, camera._getRenderTextureFormat(), Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE);
  6409. var cameraTarget = camera._renderTexture;
  6410. this._context.command.clear();
  6411. this._context.source = screenTexture;
  6412. this._context.destination = cameraTarget;
  6413. this._context.compositeShaderData.clearDefine();
  6414. this._context.command.blitScreenTriangle(cameraTarget, screenTexture);
  6415. this._context.compositeShaderData.setTexture(PostProcess.SHADERVALUE_AUTOEXPOSURETEX, Laya.Texture2D.whiteTexture);
  6416. for (var i = 0, n = this._effects.length; i < n; i++)
  6417. this._effects[i].render(this._context);
  6418. this._compositeShaderData.addDefine(PostProcess.SHADERDEFINE_FINALPASS);
  6419. var offScreenTexture = camera.renderTarget;
  6420. var dest = offScreenTexture ? offScreenTexture : null;
  6421. this._context.destination = dest;
  6422. this._context.command.blitScreenTriangle(this._context.source, dest, this._compositeShader, this._compositeShaderData);
  6423. RenderTexture.recoverToPool(screenTexture);
  6424. var tempRenderTextures = this._context.deferredReleaseTextures;
  6425. for (i = 0, n = tempRenderTextures.length; i < n; i++)
  6426. RenderTexture.recoverToPool(tempRenderTextures[i]);
  6427. tempRenderTextures.length = 0;
  6428. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(noteValue);
  6429. }
  6430. addEffect(effect) {
  6431. this._effects.push(effect);
  6432. }
  6433. removeEffect(effect) {
  6434. var index = this._effects.indexOf(effect);
  6435. if (index !== -1)
  6436. this._effects.splice(index, 1);
  6437. }
  6438. }
  6439. PostProcess.SHADERVALUE_MAINTEX = Shader3D.propertyNameToID("u_MainTex");
  6440. PostProcess.SHADERVALUE_BLOOMTEX = Shader3D.propertyNameToID("u_BloomTex");
  6441. PostProcess.SHADERVALUE_AUTOEXPOSURETEX = Shader3D.propertyNameToID("u_AutoExposureTex");
  6442. PostProcess.SHADERVALUE_BLOOM_DIRTTEX = Shader3D.propertyNameToID("u_Bloom_DirtTex");
  6443. PostProcess.SHADERVALUE_BLOOMTEX_TEXELSIZE = Shader3D.propertyNameToID("u_BloomTex_TexelSize");
  6444. PostProcess.SHADERVALUE_BLOOM_DIRTTILEOFFSET = Shader3D.propertyNameToID("u_Bloom_DirtTileOffset");
  6445. PostProcess.SHADERVALUE_BLOOM_SETTINGS = Shader3D.propertyNameToID("u_Bloom_Settings");
  6446. PostProcess.SHADERVALUE_BLOOM_COLOR = Shader3D.propertyNameToID("u_Bloom_Color");
  6447. class AnimationTransform3D extends Laya.EventDispatcher {
  6448. constructor(owner, localPosition = null, localRotation = null, localScale = null, worldMatrix = null) {
  6449. super();
  6450. this._owner = owner;
  6451. this._children = [];
  6452. this._localMatrix = new Float32Array(16);
  6453. if (Laya.Render.supportWebGLPlusAnimation) {
  6454. this._localPosition = new ConchVector3(0, 0, 0, localPosition);
  6455. this._localRotation = new ConchQuaternion(0, 0, 0, 1, localRotation);
  6456. this._localScale = new ConchVector3(0, 0, 0, localScale);
  6457. this._worldMatrix = worldMatrix;
  6458. }
  6459. else {
  6460. this._localPosition = new Vector3();
  6461. this._localRotation = new Quaternion();
  6462. this._localScale = new Vector3();
  6463. this._worldMatrix = new Float32Array(16);
  6464. }
  6465. this._localQuaternionUpdate = false;
  6466. this._locaEulerlUpdate = false;
  6467. this._localUpdate = false;
  6468. this._worldUpdate = true;
  6469. }
  6470. _getlocalMatrix() {
  6471. if (this._localUpdate) {
  6472. Utils3D._createAffineTransformationArray(this._localPosition, this._localRotation, this._localScale, this._localMatrix);
  6473. this._localUpdate = false;
  6474. }
  6475. return this._localMatrix;
  6476. }
  6477. _onWorldTransform() {
  6478. if (!this._worldUpdate) {
  6479. this._worldUpdate = true;
  6480. this.event(Laya.Event.TRANSFORM_CHANGED);
  6481. for (var i = 0, n = this._children.length; i < n; i++)
  6482. this._children[i]._onWorldTransform();
  6483. }
  6484. }
  6485. get localPosition() {
  6486. return this._localPosition;
  6487. }
  6488. set localPosition(value) {
  6489. this._localPosition = value;
  6490. this._localUpdate = true;
  6491. this._onWorldTransform();
  6492. }
  6493. get localRotation() {
  6494. if (this._localQuaternionUpdate) {
  6495. var euler = this._localRotationEuler;
  6496. Quaternion.createFromYawPitchRoll(euler.y / AnimationTransform3D._angleToRandin, euler.x / AnimationTransform3D._angleToRandin, euler.z / AnimationTransform3D._angleToRandin, this._localRotation);
  6497. this._localQuaternionUpdate = false;
  6498. }
  6499. return this._localRotation;
  6500. }
  6501. set localRotation(value) {
  6502. this._localRotation = value;
  6503. this._locaEulerlUpdate = true;
  6504. this._localQuaternionUpdate = false;
  6505. this._localUpdate = true;
  6506. this._onWorldTransform();
  6507. }
  6508. get localScale() {
  6509. return this._localScale;
  6510. }
  6511. set localScale(value) {
  6512. this._localScale = value;
  6513. this._localUpdate = true;
  6514. this._onWorldTransform();
  6515. }
  6516. get localRotationEuler() {
  6517. if (this._locaEulerlUpdate) {
  6518. this._localRotation.getYawPitchRoll(AnimationTransform3D._tempVector3);
  6519. var euler = AnimationTransform3D._tempVector3;
  6520. var localRotationEuler = this._localRotationEuler;
  6521. localRotationEuler.x = euler.y * AnimationTransform3D._angleToRandin;
  6522. localRotationEuler.y = euler.x * AnimationTransform3D._angleToRandin;
  6523. localRotationEuler.z = euler.z * AnimationTransform3D._angleToRandin;
  6524. this._locaEulerlUpdate = false;
  6525. }
  6526. return this._localRotationEuler;
  6527. }
  6528. set localRotationEuler(value) {
  6529. this._localRotationEuler = value;
  6530. this._locaEulerlUpdate = false;
  6531. this._localQuaternionUpdate = true;
  6532. this._localUpdate = true;
  6533. this._onWorldTransform();
  6534. }
  6535. getWorldMatrix() {
  6536. if (!Laya.Render.supportWebGLPlusAnimation && this._worldUpdate) {
  6537. if (this._parent != null) {
  6538. Utils3D.matrix4x4MultiplyFFF(this._parent.getWorldMatrix(), this._getlocalMatrix(), this._worldMatrix);
  6539. }
  6540. else {
  6541. var e = this._worldMatrix;
  6542. 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;
  6543. e[0] = e[5] = e[10] = e[15] = 1;
  6544. }
  6545. this._worldUpdate = false;
  6546. }
  6547. if (Laya.Render.supportWebGLPlusAnimation && this._worldUpdate) {
  6548. this._worldUpdate = false;
  6549. }
  6550. return this._worldMatrix;
  6551. }
  6552. setParent(value) {
  6553. if (this._parent !== value) {
  6554. if (this._parent) {
  6555. var parentChilds = this._parent._children;
  6556. var index = parentChilds.indexOf(this);
  6557. parentChilds.splice(index, 1);
  6558. }
  6559. if (value) {
  6560. value._children.push(this);
  6561. (value) && (this._onWorldTransform());
  6562. }
  6563. this._parent = value;
  6564. }
  6565. }
  6566. }
  6567. AnimationTransform3D._tempVector3 = new Vector3();
  6568. AnimationTransform3D._angleToRandin = 180 / Math.PI;
  6569. class AnimationNode {
  6570. constructor(localPosition = null, localRotation = null, localScale = null, worldMatrix = null) {
  6571. this._children = [];
  6572. this.transform = new AnimationTransform3D(this, localPosition, localRotation, localScale, worldMatrix);
  6573. }
  6574. addChild(child) {
  6575. child._parent = this;
  6576. child.transform.setParent(this.transform);
  6577. this._children.push(child);
  6578. }
  6579. removeChild(child) {
  6580. var index = this._children.indexOf(child);
  6581. (index !== -1) && (this._children.splice(index, 1));
  6582. }
  6583. getChildByName(name) {
  6584. for (var i = 0, n = this._children.length; i < n; i++) {
  6585. var child = this._children[i];
  6586. if (child.name === name)
  6587. return child;
  6588. }
  6589. return null;
  6590. }
  6591. getChildByIndex(index) {
  6592. return this._children[index];
  6593. }
  6594. getChildCount() {
  6595. return this._children.length;
  6596. }
  6597. cloneTo(destObject) {
  6598. var destNode = destObject;
  6599. destNode.name = this.name;
  6600. for (var i = 0, n = this._children.length; i < n; i++) {
  6601. var child = this._children[i];
  6602. var destChild = child.clone();
  6603. destNode.addChild(destChild);
  6604. var transform = child.transform;
  6605. var destTransform = destChild.transform;
  6606. var destLocalPosition = destTransform.localPosition;
  6607. var destLocalRotation = destTransform.localRotation;
  6608. var destLocalScale = destTransform.localScale;
  6609. transform.localPosition.cloneTo(destLocalPosition);
  6610. transform.localRotation.cloneTo(destLocalRotation);
  6611. transform.localScale.cloneTo(destLocalScale);
  6612. destTransform.localPosition = destLocalPosition;
  6613. destTransform.localRotation = destLocalRotation;
  6614. destTransform.localScale = destLocalScale;
  6615. }
  6616. }
  6617. clone() {
  6618. var dest = new AnimationNode();
  6619. this.cloneTo(dest);
  6620. return dest;
  6621. }
  6622. _cloneNative(localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar) {
  6623. var curID = avatar._nativeCurCloneCount;
  6624. animationNodeParentIndices[curID] = parentIndex;
  6625. var localPosition = new Float32Array(localPositions.buffer, curID * 3 * 4, 3);
  6626. var localRotation = new Float32Array(localRotations.buffer, curID * 4 * 4, 4);
  6627. var localScale = new Float32Array(localScales.buffer, curID * 3 * 4, 3);
  6628. var worldMatrix = new Float32Array(animationNodeWorldMatrixs.buffer, curID * 16 * 4, 16);
  6629. var dest = new AnimationNode(localPosition, localRotation, localScale, worldMatrix);
  6630. dest._worldMatrixIndex = curID;
  6631. this._cloneToNative(dest, localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, curID, avatar);
  6632. return dest;
  6633. }
  6634. _cloneToNative(destObject, localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar) {
  6635. var destNode = destObject;
  6636. destNode.name = this.name;
  6637. for (var i = 0, n = this._children.length; i < n; i++) {
  6638. var child = this._children[i];
  6639. avatar._nativeCurCloneCount++;
  6640. var destChild = child._cloneNative(localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar);
  6641. destNode.addChild(destChild);
  6642. var transform = child.transform;
  6643. var destTransform = destChild.transform;
  6644. var destLocalPosition = destTransform.localPosition;
  6645. var destLocalRotation = destTransform.localRotation;
  6646. var destLocalScale = destTransform.localScale;
  6647. transform.localPosition.cloneTo(destLocalPosition);
  6648. transform.localRotation.cloneTo(destLocalRotation);
  6649. transform.localScale.cloneTo(destLocalScale);
  6650. destTransform.localPosition = destLocalPosition;
  6651. destTransform.localRotation = destLocalRotation;
  6652. destTransform.localScale = destLocalScale;
  6653. }
  6654. }
  6655. }
  6656. class Avatar extends Laya.Resource {
  6657. constructor() {
  6658. super();
  6659. this._nativeNodeCount = 0;
  6660. this._nativeCurCloneCount = 0;
  6661. }
  6662. static _parse(data, propertyParams = null, constructParams = null) {
  6663. var avatar = new Avatar();
  6664. avatar._rootNode = new AnimationNode(new Float32Array(3), new Float32Array(4), new Float32Array(3), new Float32Array(16));
  6665. if (Laya.Render.supportWebGLPlusAnimation)
  6666. avatar._nativeNodeCount++;
  6667. if (data.version) {
  6668. var rootNode = data.rootNode;
  6669. (rootNode) && (avatar._parseNode(rootNode, avatar._rootNode));
  6670. }
  6671. return avatar;
  6672. }
  6673. static load(url, complete) {
  6674. Laya.ILaya.loader.create(url, complete, null, Avatar.AVATAR);
  6675. }
  6676. _initCloneToAnimator(destNode, destAnimator) {
  6677. destAnimator._avatarNodeMap[destNode.name] = destNode;
  6678. for (var i = 0, n = destNode.getChildCount(); i < n; i++)
  6679. this._initCloneToAnimator(destNode.getChildByIndex(i), destAnimator);
  6680. }
  6681. _parseNode(nodaData, node) {
  6682. var name = nodaData.props.name;
  6683. node.name = name;
  6684. var props = nodaData.props;
  6685. var transform = node.transform;
  6686. var pos = transform.localPosition;
  6687. var rot = transform.localRotation;
  6688. var sca = transform.localScale;
  6689. pos.fromArray(props.translate);
  6690. rot.fromArray(props.rotation);
  6691. sca.fromArray(props.scale);
  6692. transform.localPosition = pos;
  6693. transform.localRotation = rot;
  6694. transform.localScale = sca;
  6695. var childrenData = nodaData.child;
  6696. for (var j = 0, n = childrenData.length; j < n; j++) {
  6697. var childData = childrenData[j];
  6698. var childBone = new AnimationNode(new Float32Array(3), new Float32Array(4), new Float32Array(3), new Float32Array(16));
  6699. node.addChild(childBone);
  6700. if (Laya.Render.supportWebGLPlusAnimation)
  6701. this._nativeNodeCount++;
  6702. this._parseNode(childData, childBone);
  6703. }
  6704. }
  6705. _cloneDatasToAnimator(destAnimator) {
  6706. var destRoot;
  6707. destRoot = this._rootNode.clone();
  6708. var transform = this._rootNode.transform;
  6709. var destTransform = destRoot.transform;
  6710. var destPosition = destTransform.localPosition;
  6711. var destRotation = destTransform.localRotation;
  6712. var destScale = destTransform.localScale;
  6713. transform.localPosition.cloneTo(destPosition);
  6714. transform.localRotation.cloneTo(destRotation);
  6715. transform.localScale.cloneTo(destScale);
  6716. destTransform.localPosition = destPosition;
  6717. destTransform.localRotation = destRotation;
  6718. destTransform.localScale = destScale;
  6719. destAnimator._avatarNodeMap = {};
  6720. this._initCloneToAnimator(destRoot, destAnimator);
  6721. }
  6722. cloneTo(destObject) {
  6723. var destAvatar = destObject;
  6724. var destRoot = this._rootNode.clone();
  6725. destAvatar._rootNode = destRoot;
  6726. }
  6727. clone() {
  6728. var dest = new Avatar();
  6729. this.cloneTo(dest);
  6730. return dest;
  6731. }
  6732. _cloneDatasToAnimatorNative(destAnimator) {
  6733. var animationNodeLocalPositions = new Float32Array(this._nativeNodeCount * 3);
  6734. var animationNodeLocalRotations = new Float32Array(this._nativeNodeCount * 4);
  6735. var animationNodeLocalScales = new Float32Array(this._nativeNodeCount * 3);
  6736. var animationNodeWorldMatrixs = new Float32Array(this._nativeNodeCount * 16);
  6737. var animationNodeParentIndices = new Int16Array(this._nativeNodeCount);
  6738. destAnimator._animationNodeLocalPositions = animationNodeLocalPositions;
  6739. destAnimator._animationNodeLocalRotations = animationNodeLocalRotations;
  6740. destAnimator._animationNodeLocalScales = animationNodeLocalScales;
  6741. destAnimator._animationNodeWorldMatrixs = animationNodeWorldMatrixs;
  6742. destAnimator._animationNodeParentIndices = animationNodeParentIndices;
  6743. this._nativeCurCloneCount = 0;
  6744. var destRoot = this._rootNode._cloneNative(animationNodeLocalPositions, animationNodeLocalRotations, animationNodeLocalScales, animationNodeWorldMatrixs, animationNodeParentIndices, -1, this);
  6745. var transform = this._rootNode.transform;
  6746. var destTransform = destRoot.transform;
  6747. var destPosition = destTransform.localPosition;
  6748. var destRotation = destTransform.localRotation;
  6749. var destScale = destTransform.localScale;
  6750. transform.localPosition.cloneTo(destPosition);
  6751. transform.localRotation.cloneTo(destRotation);
  6752. transform.localScale.cloneTo(destScale);
  6753. destTransform.localPosition = destPosition;
  6754. destTransform.localRotation = destRotation;
  6755. destTransform.localScale = destScale;
  6756. destAnimator._avatarNodeMap = {};
  6757. this._initCloneToAnimator(destRoot, destAnimator);
  6758. }
  6759. }
  6760. Avatar.AVATAR = "AVATAR";
  6761. class BaseMaterial extends Laya.Resource {
  6762. constructor() {
  6763. super();
  6764. this._shaderValues = null;
  6765. this._disablePublicDefineDatas = new DefineDatas();
  6766. this._shaderValues = new ShaderData(this);
  6767. this.renderQueue = BaseMaterial.RENDERQUEUE_OPAQUE;
  6768. this._alphaTest = false;
  6769. }
  6770. static load(url, complete) {
  6771. Laya.Laya.loader.create(url, complete, null, BaseMaterial.MATERIAL);
  6772. }
  6773. static __initDefine__() {
  6774. BaseMaterial.SHADERDEFINE_ALPHATEST = Shader3D.getDefineByName("ALPHATEST");
  6775. }
  6776. static _parse(data, propertyParams = null, constructParams = null) {
  6777. var jsonData = data;
  6778. var props = jsonData.props;
  6779. var material;
  6780. var classType = props.type;
  6781. var clas = Laya.ClassUtils.getRegClass(classType);
  6782. if (clas)
  6783. material = new clas();
  6784. else
  6785. throw ('_getSprite3DHierarchyInnerUrls 错误: ' + data.type + ' 不是类');
  6786. switch (jsonData.version) {
  6787. case "LAYAMATERIAL:01":
  6788. case "LAYAMATERIAL:02":
  6789. var i, n;
  6790. for (var key in props) {
  6791. switch (key) {
  6792. case "vectors":
  6793. var vectors = props[key];
  6794. for (i = 0, n = vectors.length; i < n; i++) {
  6795. var vector = vectors[i];
  6796. var vectorValue = vector.value;
  6797. switch (vectorValue.length) {
  6798. case 2:
  6799. material[vector.name] = new Vector2(vectorValue[0], vectorValue[1]);
  6800. break;
  6801. case 3:
  6802. material[vector.name] = new Vector3(vectorValue[0], vectorValue[1], vectorValue[2]);
  6803. break;
  6804. case 4:
  6805. material[vector.name] = new Vector4(vectorValue[0], vectorValue[1], vectorValue[2], vectorValue[3]);
  6806. break;
  6807. default:
  6808. throw new Error("BaseMaterial:unkonwn color length.");
  6809. }
  6810. }
  6811. break;
  6812. case "textures":
  6813. var textures = props[key];
  6814. for (i = 0, n = textures.length; i < n; i++) {
  6815. var texture = textures[i];
  6816. var path = texture.path;
  6817. (path) && (material[texture.name] = Laya.Loader.getRes(path));
  6818. }
  6819. break;
  6820. case "defines":
  6821. var defineNames = props[key];
  6822. for (i = 0, n = defineNames.length; i < n; i++) {
  6823. var define = Shader3D.getDefineByName(defineNames[i]);
  6824. material._shaderValues.addDefine(define);
  6825. }
  6826. break;
  6827. case "renderStates":
  6828. var renderStatesData = props[key];
  6829. var renderStateData = renderStatesData[0];
  6830. var mat = material;
  6831. mat.blend = renderStateData.blend;
  6832. mat.cull = renderStateData.cull;
  6833. mat.depthTest = renderStateData.depthTest;
  6834. mat.depthWrite = renderStateData.depthWrite;
  6835. mat.blendSrc = renderStateData.srcBlend;
  6836. mat.blendDst = renderStateData.dstBlend;
  6837. break;
  6838. case "cull":
  6839. material.cull = props[key];
  6840. break;
  6841. case "blend":
  6842. material.blend = props[key];
  6843. break;
  6844. case "depthWrite":
  6845. material.depthWrite = props[key];
  6846. break;
  6847. case "srcBlend":
  6848. material.blendSrc = props[key];
  6849. break;
  6850. case "dstBlend":
  6851. material.blendDst = props[key];
  6852. break;
  6853. default:
  6854. material[key] = props[key];
  6855. }
  6856. }
  6857. break;
  6858. default:
  6859. throw new Error("BaseMaterial:unkonwn version.");
  6860. }
  6861. return material;
  6862. }
  6863. get alphaTestValue() {
  6864. return this._shaderValues.getNumber(BaseMaterial.ALPHATESTVALUE);
  6865. }
  6866. set alphaTestValue(value) {
  6867. this._shaderValues.setNumber(BaseMaterial.ALPHATESTVALUE, value);
  6868. }
  6869. get alphaTest() {
  6870. return this._alphaTest;
  6871. }
  6872. set alphaTest(value) {
  6873. this._alphaTest = value;
  6874. if (value)
  6875. this._shaderValues.addDefine(BaseMaterial.SHADERDEFINE_ALPHATEST);
  6876. else
  6877. this._shaderValues.removeDefine(BaseMaterial.SHADERDEFINE_ALPHATEST);
  6878. }
  6879. _removeTetxureReference() {
  6880. var data = this._shaderValues.getData();
  6881. for (var k in data) {
  6882. var value = data[k];
  6883. if (value && value instanceof Laya.BaseTexture)
  6884. value._removeReference();
  6885. }
  6886. }
  6887. _addReference(count = 1) {
  6888. super._addReference(count);
  6889. var data = this._shaderValues.getData();
  6890. for (var k in data) {
  6891. var value = data[k];
  6892. if (value && value instanceof Laya.BaseTexture)
  6893. value._addReference();
  6894. }
  6895. }
  6896. _removeReference(count = 1) {
  6897. super._removeReference(count);
  6898. this._removeTetxureReference();
  6899. }
  6900. _disposeResource() {
  6901. if (this._referenceCount > 0)
  6902. this._removeTetxureReference();
  6903. this._shaderValues = null;
  6904. }
  6905. setShaderName(name) {
  6906. this._shader = Shader3D.find(name);
  6907. if (!this._shader)
  6908. throw new Error("BaseMaterial: unknown shader name.");
  6909. }
  6910. cloneTo(destObject) {
  6911. var destBaseMaterial = destObject;
  6912. destBaseMaterial.name = this.name;
  6913. destBaseMaterial.renderQueue = this.renderQueue;
  6914. this._disablePublicDefineDatas.cloneTo(destBaseMaterial._disablePublicDefineDatas);
  6915. this._shaderValues.cloneTo(destBaseMaterial._shaderValues);
  6916. }
  6917. clone() {
  6918. var dest = new BaseMaterial();
  6919. this.cloneTo(dest);
  6920. return dest;
  6921. }
  6922. get _defineDatas() {
  6923. return this._shaderValues._defineDatas;
  6924. }
  6925. }
  6926. BaseMaterial.MATERIAL = "MATERIAL";
  6927. BaseMaterial.RENDERQUEUE_OPAQUE = 2000;
  6928. BaseMaterial.RENDERQUEUE_ALPHATEST = 2450;
  6929. BaseMaterial.RENDERQUEUE_TRANSPARENT = 3000;
  6930. BaseMaterial.ALPHATESTVALUE = Shader3D.propertyNameToID("u_AlphaTestValue");
  6931. BaseMaterial.SHADERDEFINE_ALPHATEST = null;
  6932. class Scene3DShaderDeclaration {
  6933. }
  6934. class RenderState {
  6935. constructor() {
  6936. this.cull = RenderState.CULL_BACK;
  6937. this.blend = RenderState.BLEND_DISABLE;
  6938. this.srcBlend = RenderState.BLENDPARAM_ONE;
  6939. this.dstBlend = RenderState.BLENDPARAM_ZERO;
  6940. this.srcBlendRGB = RenderState.BLENDPARAM_ONE;
  6941. this.dstBlendRGB = RenderState.BLENDPARAM_ZERO;
  6942. this.srcBlendAlpha = RenderState.BLENDPARAM_ONE;
  6943. this.dstBlendAlpha = RenderState.BLENDPARAM_ZERO;
  6944. this.blendConstColor = new Vector4(1, 1, 1, 1);
  6945. this.blendEquation = RenderState.BLENDEQUATION_ADD;
  6946. this.blendEquationRGB = RenderState.BLENDEQUATION_ADD;
  6947. this.blendEquationAlpha = RenderState.BLENDEQUATION_ADD;
  6948. this.depthTest = RenderState.DEPTHTEST_LEQUAL;
  6949. this.depthWrite = true;
  6950. }
  6951. cloneTo(dest) {
  6952. var destState = dest;
  6953. destState.cull = this.cull;
  6954. destState.blend = this.blend;
  6955. destState.srcBlend = this.srcBlend;
  6956. destState.dstBlend = this.dstBlend;
  6957. destState.srcBlendRGB = this.srcBlendRGB;
  6958. destState.dstBlendRGB = this.dstBlendRGB;
  6959. destState.srcBlendAlpha = this.srcBlendAlpha;
  6960. destState.dstBlendAlpha = this.dstBlendAlpha;
  6961. this.blendConstColor.cloneTo(destState.blendConstColor);
  6962. destState.blendEquation = this.blendEquation;
  6963. destState.blendEquationRGB = this.blendEquationRGB;
  6964. destState.blendEquationAlpha = this.blendEquationAlpha;
  6965. destState.depthTest = this.depthTest;
  6966. destState.depthWrite = this.depthWrite;
  6967. }
  6968. clone() {
  6969. var dest = new RenderState();
  6970. this.cloneTo(dest);
  6971. return dest;
  6972. }
  6973. }
  6974. RenderState.CULL_NONE = 0;
  6975. RenderState.CULL_FRONT = 1;
  6976. RenderState.CULL_BACK = 2;
  6977. RenderState.BLEND_DISABLE = 0;
  6978. RenderState.BLEND_ENABLE_ALL = 1;
  6979. RenderState.BLEND_ENABLE_SEPERATE = 2;
  6980. RenderState.BLENDPARAM_ZERO = 0;
  6981. RenderState.BLENDPARAM_ONE = 1;
  6982. RenderState.BLENDPARAM_SRC_COLOR = 0x0300;
  6983. RenderState.BLENDPARAM_ONE_MINUS_SRC_COLOR = 0x0301;
  6984. RenderState.BLENDPARAM_DST_COLOR = 0x0306;
  6985. RenderState.BLENDPARAM_ONE_MINUS_DST_COLOR = 0x0307;
  6986. RenderState.BLENDPARAM_SRC_ALPHA = 0x0302;
  6987. RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA = 0x0303;
  6988. RenderState.BLENDPARAM_DST_ALPHA = 0x0304;
  6989. RenderState.BLENDPARAM_ONE_MINUS_DST_ALPHA = 0x0305;
  6990. RenderState.BLENDPARAM_SRC_ALPHA_SATURATE = 0x0308;
  6991. RenderState.BLENDEQUATION_ADD = 0x8006;
  6992. RenderState.BLENDEQUATION_SUBTRACT = 0x800A;
  6993. RenderState.BLENDEQUATION_REVERSE_SUBTRACT = 0x800B;
  6994. RenderState.DEPTHTEST_OFF = 0;
  6995. RenderState.DEPTHTEST_NEVER = 0x0200;
  6996. RenderState.DEPTHTEST_LESS = 0x0201;
  6997. RenderState.DEPTHTEST_EQUAL = 0x0202;
  6998. RenderState.DEPTHTEST_LEQUAL = 0x0203;
  6999. RenderState.DEPTHTEST_GREATER = 0x0204;
  7000. RenderState.DEPTHTEST_NOTEQUAL = 0x0205;
  7001. RenderState.DEPTHTEST_GEQUAL = 0x0206;
  7002. RenderState.DEPTHTEST_ALWAYS = 0x0207;
  7003. class BlinnPhongMaterial extends BaseMaterial {
  7004. constructor() {
  7005. super();
  7006. this._enableVertexColor = false;
  7007. this.setShaderName("BLINNPHONG");
  7008. this._albedoIntensity = 1.0;
  7009. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  7010. var sv = this._shaderValues;
  7011. sv.setVector(BlinnPhongMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  7012. sv.setVector(BlinnPhongMaterial.MATERIALSPECULAR, new Vector4(1.0, 1.0, 1.0, 1.0));
  7013. sv.setNumber(BlinnPhongMaterial.SHININESS, 0.078125);
  7014. sv.setNumber(BaseMaterial.ALPHATESTVALUE, 0.5);
  7015. sv.setVector(BlinnPhongMaterial.TILINGOFFSET, new Vector4(1.0, 1.0, 0.0, 0.0));
  7016. this._enableLighting = true;
  7017. this.renderMode = BlinnPhongMaterial.RENDERMODE_OPAQUE;
  7018. }
  7019. static __initDefine__() {
  7020. BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP = Shader3D.getDefineByName("DIFFUSEMAP");
  7021. BlinnPhongMaterial.SHADERDEFINE_NORMALMAP = Shader3D.getDefineByName("NORMALMAP");
  7022. BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP = Shader3D.getDefineByName("SPECULARMAP");
  7023. BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  7024. BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR = Shader3D.getDefineByName("ENABLEVERTEXCOLOR");
  7025. }
  7026. get _ColorR() {
  7027. return this._albedoColor.x;
  7028. }
  7029. set _ColorR(value) {
  7030. this._albedoColor.x = value;
  7031. this.albedoColor = this._albedoColor;
  7032. }
  7033. get _ColorG() {
  7034. return this._albedoColor.y;
  7035. }
  7036. set _ColorG(value) {
  7037. this._albedoColor.y = value;
  7038. this.albedoColor = this._albedoColor;
  7039. }
  7040. get _ColorB() {
  7041. return this._albedoColor.z;
  7042. }
  7043. set _ColorB(value) {
  7044. this._albedoColor.z = value;
  7045. this.albedoColor = this._albedoColor;
  7046. }
  7047. get _ColorA() {
  7048. return this._albedoColor.w;
  7049. }
  7050. set _ColorA(value) {
  7051. this._albedoColor.w = value;
  7052. this.albedoColor = this._albedoColor;
  7053. }
  7054. get _SpecColorR() {
  7055. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).x;
  7056. }
  7057. set _SpecColorR(value) {
  7058. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).x = value;
  7059. }
  7060. get _SpecColorG() {
  7061. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).y;
  7062. }
  7063. set _SpecColorG(value) {
  7064. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).y = value;
  7065. }
  7066. get _SpecColorB() {
  7067. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).z;
  7068. }
  7069. set _SpecColorB(value) {
  7070. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).z = value;
  7071. }
  7072. get _SpecColorA() {
  7073. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).w;
  7074. }
  7075. set _SpecColorA(value) {
  7076. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).w = value;
  7077. }
  7078. get _AlbedoIntensity() {
  7079. return this._albedoIntensity;
  7080. }
  7081. set _AlbedoIntensity(value) {
  7082. if (this._albedoIntensity !== value) {
  7083. var finalAlbedo = this._shaderValues.getVector(BlinnPhongMaterial.ALBEDOCOLOR);
  7084. Vector4.scale(this._albedoColor, value, finalAlbedo);
  7085. this._albedoIntensity = value;
  7086. this._shaderValues.setVector(BlinnPhongMaterial.ALBEDOCOLOR, finalAlbedo);
  7087. }
  7088. }
  7089. get _Shininess() {
  7090. return this._shaderValues.getNumber(BlinnPhongMaterial.SHININESS);
  7091. }
  7092. set _Shininess(value) {
  7093. value = Math.max(0.0, Math.min(1.0, value));
  7094. this._shaderValues.setNumber(BlinnPhongMaterial.SHININESS, value);
  7095. }
  7096. get _MainTex_STX() {
  7097. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).x;
  7098. }
  7099. set _MainTex_STX(x) {
  7100. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  7101. tilOff.x = x;
  7102. this.tilingOffset = tilOff;
  7103. }
  7104. get _MainTex_STY() {
  7105. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).y;
  7106. }
  7107. set _MainTex_STY(y) {
  7108. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  7109. tilOff.y = y;
  7110. this.tilingOffset = tilOff;
  7111. }
  7112. get _MainTex_STZ() {
  7113. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).z;
  7114. }
  7115. set _MainTex_STZ(z) {
  7116. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  7117. tilOff.z = z;
  7118. this.tilingOffset = tilOff;
  7119. }
  7120. get _MainTex_STW() {
  7121. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).w;
  7122. }
  7123. set _MainTex_STW(w) {
  7124. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  7125. tilOff.w = w;
  7126. this.tilingOffset = tilOff;
  7127. }
  7128. get _Cutoff() {
  7129. return this.alphaTestValue;
  7130. }
  7131. set _Cutoff(value) {
  7132. this.alphaTestValue = value;
  7133. }
  7134. set renderMode(value) {
  7135. switch (value) {
  7136. case BlinnPhongMaterial.RENDERMODE_OPAQUE:
  7137. this.alphaTest = false;
  7138. this.renderQueue = BaseMaterial.RENDERQUEUE_OPAQUE;
  7139. this.depthWrite = true;
  7140. this.cull = RenderState.CULL_BACK;
  7141. this.blend = RenderState.BLEND_DISABLE;
  7142. this.depthTest = RenderState.DEPTHTEST_LESS;
  7143. break;
  7144. case BlinnPhongMaterial.RENDERMODE_CUTOUT:
  7145. this.renderQueue = BaseMaterial.RENDERQUEUE_ALPHATEST;
  7146. this.alphaTest = true;
  7147. this.depthWrite = true;
  7148. this.cull = RenderState.CULL_BACK;
  7149. this.blend = RenderState.BLEND_DISABLE;
  7150. this.depthTest = RenderState.DEPTHTEST_LESS;
  7151. break;
  7152. case BlinnPhongMaterial.RENDERMODE_TRANSPARENT:
  7153. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  7154. this.alphaTest = false;
  7155. this.depthWrite = false;
  7156. this.cull = RenderState.CULL_BACK;
  7157. this.blend = RenderState.BLEND_ENABLE_ALL;
  7158. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  7159. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  7160. this.depthTest = RenderState.DEPTHTEST_LESS;
  7161. break;
  7162. default:
  7163. throw new Error("Material:renderMode value error.");
  7164. }
  7165. }
  7166. get enableVertexColor() {
  7167. return this._enableVertexColor;
  7168. }
  7169. set enableVertexColor(value) {
  7170. this._enableVertexColor = value;
  7171. if (value)
  7172. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  7173. else
  7174. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  7175. }
  7176. get tilingOffsetX() {
  7177. return this._MainTex_STX;
  7178. }
  7179. set tilingOffsetX(x) {
  7180. this._MainTex_STX = x;
  7181. }
  7182. get tilingOffsetY() {
  7183. return this._MainTex_STY;
  7184. }
  7185. set tilingOffsetY(y) {
  7186. this._MainTex_STY = y;
  7187. }
  7188. get tilingOffsetZ() {
  7189. return this._MainTex_STZ;
  7190. }
  7191. set tilingOffsetZ(z) {
  7192. this._MainTex_STZ = z;
  7193. }
  7194. get tilingOffsetW() {
  7195. return this._MainTex_STW;
  7196. }
  7197. set tilingOffsetW(w) {
  7198. this._MainTex_STW = w;
  7199. }
  7200. get tilingOffset() {
  7201. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  7202. }
  7203. set tilingOffset(value) {
  7204. if (value) {
  7205. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  7206. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  7207. else
  7208. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  7209. }
  7210. else {
  7211. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  7212. }
  7213. this._shaderValues.setVector(BlinnPhongMaterial.TILINGOFFSET, value);
  7214. }
  7215. get albedoColorR() {
  7216. return this._ColorR;
  7217. }
  7218. set albedoColorR(value) {
  7219. this._ColorR = value;
  7220. }
  7221. get albedoColorG() {
  7222. return this._ColorG;
  7223. }
  7224. set albedoColorG(value) {
  7225. this._ColorG = value;
  7226. }
  7227. get albedoColorB() {
  7228. return this._ColorB;
  7229. }
  7230. set albedoColorB(value) {
  7231. this._ColorB = value;
  7232. }
  7233. get albedoColorA() {
  7234. return this._ColorA;
  7235. }
  7236. set albedoColorA(value) {
  7237. this._ColorA = value;
  7238. }
  7239. get albedoColor() {
  7240. return this._albedoColor;
  7241. }
  7242. set albedoColor(value) {
  7243. var finalAlbedo = this._shaderValues.getVector(BlinnPhongMaterial.ALBEDOCOLOR);
  7244. Vector4.scale(value, this._albedoIntensity, finalAlbedo);
  7245. this._albedoColor = value;
  7246. this._shaderValues.setVector(BlinnPhongMaterial.ALBEDOCOLOR, finalAlbedo);
  7247. }
  7248. get albedoIntensity() {
  7249. return this._albedoIntensity;
  7250. }
  7251. set albedoIntensity(value) {
  7252. this._AlbedoIntensity = value;
  7253. }
  7254. get specularColorR() {
  7255. return this._SpecColorR;
  7256. }
  7257. set specularColorR(value) {
  7258. this._SpecColorR = value;
  7259. }
  7260. get specularColorG() {
  7261. return this._SpecColorG;
  7262. }
  7263. set specularColorG(value) {
  7264. this._SpecColorG = value;
  7265. }
  7266. get specularColorB() {
  7267. return this._SpecColorB;
  7268. }
  7269. set specularColorB(value) {
  7270. this._SpecColorB = value;
  7271. }
  7272. get specularColorA() {
  7273. return this._SpecColorA;
  7274. }
  7275. set specularColorA(value) {
  7276. this._SpecColorA = value;
  7277. }
  7278. get specularColor() {
  7279. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR);
  7280. }
  7281. set specularColor(value) {
  7282. this._shaderValues.setVector(BlinnPhongMaterial.MATERIALSPECULAR, value);
  7283. }
  7284. get shininess() {
  7285. return this._Shininess;
  7286. }
  7287. set shininess(value) {
  7288. this._Shininess = value;
  7289. }
  7290. get albedoTexture() {
  7291. return this._shaderValues.getTexture(BlinnPhongMaterial.ALBEDOTEXTURE);
  7292. }
  7293. set albedoTexture(value) {
  7294. if (value)
  7295. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP);
  7296. else
  7297. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP);
  7298. this._shaderValues.setTexture(BlinnPhongMaterial.ALBEDOTEXTURE, value);
  7299. }
  7300. get normalTexture() {
  7301. return this._shaderValues.getTexture(BlinnPhongMaterial.NORMALTEXTURE);
  7302. }
  7303. set normalTexture(value) {
  7304. if (value)
  7305. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_NORMALMAP);
  7306. else
  7307. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_NORMALMAP);
  7308. this._shaderValues.setTexture(BlinnPhongMaterial.NORMALTEXTURE, value);
  7309. }
  7310. get specularTexture() {
  7311. return this._shaderValues.getTexture(BlinnPhongMaterial.SPECULARTEXTURE);
  7312. }
  7313. set specularTexture(value) {
  7314. if (value)
  7315. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP);
  7316. else
  7317. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP);
  7318. this._shaderValues.setTexture(BlinnPhongMaterial.SPECULARTEXTURE, value);
  7319. }
  7320. get enableLighting() {
  7321. return this._enableLighting;
  7322. }
  7323. set enableLighting(value) {
  7324. if (this._enableLighting !== value) {
  7325. if (value) {
  7326. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  7327. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  7328. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  7329. }
  7330. else {
  7331. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  7332. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  7333. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  7334. }
  7335. this._enableLighting = value;
  7336. }
  7337. }
  7338. get depthWrite() {
  7339. return this._shaderValues.getBool(BlinnPhongMaterial.DEPTH_WRITE);
  7340. }
  7341. set depthWrite(value) {
  7342. this._shaderValues.setBool(BlinnPhongMaterial.DEPTH_WRITE, value);
  7343. }
  7344. get cull() {
  7345. return this._shaderValues.getInt(BlinnPhongMaterial.CULL);
  7346. }
  7347. set cull(value) {
  7348. this._shaderValues.setInt(BlinnPhongMaterial.CULL, value);
  7349. }
  7350. get blend() {
  7351. return this._shaderValues.getInt(BlinnPhongMaterial.BLEND);
  7352. }
  7353. set blend(value) {
  7354. this._shaderValues.setInt(BlinnPhongMaterial.BLEND, value);
  7355. }
  7356. get blendSrc() {
  7357. return this._shaderValues.getInt(BlinnPhongMaterial.BLEND_SRC);
  7358. }
  7359. set blendSrc(value) {
  7360. this._shaderValues.setInt(BlinnPhongMaterial.BLEND_SRC, value);
  7361. }
  7362. get blendDst() {
  7363. return this._shaderValues.getInt(BlinnPhongMaterial.BLEND_DST);
  7364. }
  7365. set blendDst(value) {
  7366. this._shaderValues.setInt(BlinnPhongMaterial.BLEND_DST, value);
  7367. }
  7368. get depthTest() {
  7369. return this._shaderValues.getInt(BlinnPhongMaterial.DEPTH_TEST);
  7370. }
  7371. set depthTest(value) {
  7372. this._shaderValues.setInt(BlinnPhongMaterial.DEPTH_TEST, value);
  7373. }
  7374. clone() {
  7375. var dest = new BlinnPhongMaterial();
  7376. this.cloneTo(dest);
  7377. return dest;
  7378. }
  7379. cloneTo(destObject) {
  7380. super.cloneTo(destObject);
  7381. var destMaterial = destObject;
  7382. destMaterial._enableLighting = this._enableLighting;
  7383. destMaterial._albedoIntensity = this._albedoIntensity;
  7384. destMaterial._enableVertexColor = this._enableVertexColor;
  7385. this._albedoColor.cloneTo(destMaterial._albedoColor);
  7386. }
  7387. }
  7388. BlinnPhongMaterial.RENDERMODE_OPAQUE = 0;
  7389. BlinnPhongMaterial.RENDERMODE_CUTOUT = 1;
  7390. BlinnPhongMaterial.RENDERMODE_TRANSPARENT = 2;
  7391. BlinnPhongMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_DiffuseTexture");
  7392. BlinnPhongMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  7393. BlinnPhongMaterial.SPECULARTEXTURE = Shader3D.propertyNameToID("u_SpecularTexture");
  7394. BlinnPhongMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_DiffuseColor");
  7395. BlinnPhongMaterial.MATERIALSPECULAR = Shader3D.propertyNameToID("u_MaterialSpecular");
  7396. BlinnPhongMaterial.SHININESS = Shader3D.propertyNameToID("u_Shininess");
  7397. BlinnPhongMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  7398. BlinnPhongMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  7399. BlinnPhongMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  7400. BlinnPhongMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  7401. BlinnPhongMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  7402. BlinnPhongMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  7403. BlinnPhongMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  7404. class EffectMaterial extends BaseMaterial {
  7405. constructor() {
  7406. super();
  7407. this.setShaderName("Effect");
  7408. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  7409. this._shaderValues.setVector(EffectMaterial.TINTCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  7410. this.renderMode = EffectMaterial.RENDERMODE_ADDTIVE;
  7411. }
  7412. static __initDefine__() {
  7413. EffectMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  7414. EffectMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  7415. EffectMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  7416. }
  7417. get _TintColorR() {
  7418. return this._color.x;
  7419. }
  7420. set _TintColorR(value) {
  7421. this._color.x = value;
  7422. this.color = this._color;
  7423. }
  7424. get _TintColorG() {
  7425. return this._color.y;
  7426. }
  7427. set _TintColorG(value) {
  7428. this._color.y = value;
  7429. this.color = this._color;
  7430. }
  7431. get _TintColorB() {
  7432. return this._color.z;
  7433. }
  7434. set _TintColorB(value) {
  7435. this._color.z = value;
  7436. this.color = this._color;
  7437. }
  7438. get _TintColorA() {
  7439. return this._color.w;
  7440. }
  7441. set _TintColorA(value) {
  7442. this._color.w = value;
  7443. this.color = this._color;
  7444. }
  7445. get _MainTex_STX() {
  7446. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).x;
  7447. }
  7448. set _MainTex_STX(x) {
  7449. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  7450. tilOff.x = x;
  7451. this.tilingOffset = tilOff;
  7452. }
  7453. get _MainTex_STY() {
  7454. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).y;
  7455. }
  7456. set _MainTex_STY(y) {
  7457. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  7458. tilOff.y = y;
  7459. this.tilingOffset = tilOff;
  7460. }
  7461. get _MainTex_STZ() {
  7462. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).z;
  7463. }
  7464. set _MainTex_STZ(z) {
  7465. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  7466. tilOff.z = z;
  7467. this.tilingOffset = tilOff;
  7468. }
  7469. get _MainTex_STW() {
  7470. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).w;
  7471. }
  7472. set _MainTex_STW(w) {
  7473. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  7474. tilOff.w = w;
  7475. this.tilingOffset = tilOff;
  7476. }
  7477. set renderMode(value) {
  7478. switch (value) {
  7479. case EffectMaterial.RENDERMODE_ADDTIVE:
  7480. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  7481. this.alphaTest = false;
  7482. this.depthWrite = false;
  7483. this.cull = RenderState.CULL_NONE;
  7484. this.blend = RenderState.BLEND_ENABLE_ALL;
  7485. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  7486. this.blendDst = RenderState.BLENDPARAM_ONE;
  7487. this.depthTest = RenderState.DEPTHTEST_LESS;
  7488. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_ADDTIVEFOG);
  7489. break;
  7490. case EffectMaterial.RENDERMODE_ALPHABLENDED:
  7491. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  7492. this.alphaTest = false;
  7493. this.depthWrite = false;
  7494. this.cull = RenderState.CULL_NONE;
  7495. this.blend = RenderState.BLEND_ENABLE_ALL;
  7496. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  7497. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  7498. this.depthTest = RenderState.DEPTHTEST_LESS;
  7499. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_ADDTIVEFOG);
  7500. break;
  7501. default:
  7502. throw new Error("MeshEffectMaterial : renderMode value error.");
  7503. }
  7504. }
  7505. get colorR() {
  7506. return this._TintColorR;
  7507. }
  7508. set colorR(value) {
  7509. this._TintColorR = value;
  7510. }
  7511. get colorG() {
  7512. return this._TintColorG;
  7513. }
  7514. set colorG(value) {
  7515. this._TintColorG = value;
  7516. }
  7517. get colorB() {
  7518. return this._TintColorB;
  7519. }
  7520. set colorB(value) {
  7521. this._TintColorB = value;
  7522. }
  7523. get colorA() {
  7524. return this._TintColorA;
  7525. }
  7526. set colorA(value) {
  7527. this._TintColorA = value;
  7528. }
  7529. get color() {
  7530. return this._shaderValues.getVector(EffectMaterial.TINTCOLOR);
  7531. }
  7532. set color(value) {
  7533. this._shaderValues.setVector(EffectMaterial.TINTCOLOR, value);
  7534. }
  7535. get texture() {
  7536. return this._shaderValues.getTexture(EffectMaterial.MAINTEXTURE);
  7537. }
  7538. set texture(value) {
  7539. if (value)
  7540. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_MAINTEXTURE);
  7541. else
  7542. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_MAINTEXTURE);
  7543. this._shaderValues.setTexture(EffectMaterial.MAINTEXTURE, value);
  7544. }
  7545. get tilingOffsetX() {
  7546. return this._MainTex_STX;
  7547. }
  7548. set tilingOffsetX(x) {
  7549. this._MainTex_STX = x;
  7550. }
  7551. get tilingOffsetY() {
  7552. return this._MainTex_STY;
  7553. }
  7554. set tilingOffsetY(y) {
  7555. this._MainTex_STY = y;
  7556. }
  7557. get tilingOffsetZ() {
  7558. return this._MainTex_STZ;
  7559. }
  7560. set tilingOffsetZ(z) {
  7561. this._MainTex_STZ = z;
  7562. }
  7563. get tilingOffsetW() {
  7564. return this._MainTex_STW;
  7565. }
  7566. set tilingOffsetW(w) {
  7567. this._MainTex_STW = w;
  7568. }
  7569. get tilingOffset() {
  7570. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  7571. }
  7572. set tilingOffset(value) {
  7573. if (value) {
  7574. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  7575. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  7576. else
  7577. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  7578. }
  7579. else {
  7580. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  7581. }
  7582. this._shaderValues.setVector(EffectMaterial.TILINGOFFSET, value);
  7583. }
  7584. set depthWrite(value) {
  7585. this._shaderValues.setBool(EffectMaterial.DEPTH_WRITE, value);
  7586. }
  7587. get depthWrite() {
  7588. return this._shaderValues.getBool(EffectMaterial.DEPTH_WRITE);
  7589. }
  7590. set cull(value) {
  7591. this._shaderValues.setInt(EffectMaterial.CULL, value);
  7592. }
  7593. get cull() {
  7594. return this._shaderValues.getInt(EffectMaterial.CULL);
  7595. }
  7596. set blend(value) {
  7597. this._shaderValues.setInt(EffectMaterial.BLEND, value);
  7598. }
  7599. get blend() {
  7600. return this._shaderValues.getInt(EffectMaterial.BLEND);
  7601. }
  7602. set blendSrc(value) {
  7603. this._shaderValues.setInt(EffectMaterial.BLEND_SRC, value);
  7604. }
  7605. get blendSrc() {
  7606. return this._shaderValues.getInt(EffectMaterial.BLEND_SRC);
  7607. }
  7608. set blendDst(value) {
  7609. this._shaderValues.setInt(EffectMaterial.BLEND_DST, value);
  7610. }
  7611. get blendDst() {
  7612. return this._shaderValues.getInt(EffectMaterial.BLEND_DST);
  7613. }
  7614. set depthTest(value) {
  7615. this._shaderValues.setInt(EffectMaterial.DEPTH_TEST, value);
  7616. }
  7617. get depthTest() {
  7618. return this._shaderValues.getInt(EffectMaterial.DEPTH_TEST);
  7619. }
  7620. clone() {
  7621. var dest = new EffectMaterial();
  7622. this.cloneTo(dest);
  7623. return dest;
  7624. }
  7625. }
  7626. EffectMaterial.RENDERMODE_ADDTIVE = 0;
  7627. EffectMaterial.RENDERMODE_ALPHABLENDED = 1;
  7628. EffectMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  7629. EffectMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  7630. EffectMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  7631. EffectMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  7632. EffectMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  7633. EffectMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  7634. EffectMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  7635. EffectMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  7636. EffectMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  7637. class ExtendTerrainMaterial extends BaseMaterial {
  7638. constructor() {
  7639. super();
  7640. this._enableLighting = true;
  7641. this.setShaderName("ExtendTerrain");
  7642. this.renderMode = ExtendTerrainMaterial.RENDERMODE_OPAQUE;
  7643. }
  7644. static __initDefine__() {
  7645. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM1");
  7646. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM2");
  7647. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM3");
  7648. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM4");
  7649. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM5");
  7650. }
  7651. get splatAlphaTexture() {
  7652. return this._shaderValues.getTexture(ExtendTerrainMaterial.SPLATALPHATEXTURE);
  7653. }
  7654. set splatAlphaTexture(value) {
  7655. this._shaderValues.setTexture(ExtendTerrainMaterial.SPLATALPHATEXTURE, value);
  7656. }
  7657. set diffuseTexture1(value) {
  7658. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE1, value);
  7659. this._setDetailNum(1);
  7660. }
  7661. get diffuseTexture2() {
  7662. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE2);
  7663. }
  7664. set diffuseTexture2(value) {
  7665. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE2, value);
  7666. this._setDetailNum(2);
  7667. }
  7668. get diffuseTexture3() {
  7669. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE3);
  7670. }
  7671. set diffuseTexture3(value) {
  7672. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE3, value);
  7673. this._setDetailNum(3);
  7674. }
  7675. get diffuseTexture4() {
  7676. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE4);
  7677. }
  7678. set diffuseTexture4(value) {
  7679. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE4, value);
  7680. this._setDetailNum(4);
  7681. }
  7682. get diffuseTexture5() {
  7683. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE5);
  7684. }
  7685. set diffuseTexture5(value) {
  7686. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE5, value);
  7687. this._setDetailNum(5);
  7688. }
  7689. _setDetailNum(value) {
  7690. switch (value) {
  7691. case 1:
  7692. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  7693. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  7694. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  7695. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  7696. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  7697. break;
  7698. case 2:
  7699. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  7700. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  7701. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  7702. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  7703. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  7704. break;
  7705. case 3:
  7706. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  7707. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  7708. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  7709. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  7710. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  7711. break;
  7712. case 4:
  7713. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  7714. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  7715. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  7716. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  7717. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  7718. break;
  7719. case 5:
  7720. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  7721. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  7722. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  7723. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  7724. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  7725. break;
  7726. }
  7727. }
  7728. set diffuseScaleOffset1(scaleOffset1) {
  7729. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET1, scaleOffset1);
  7730. }
  7731. set diffuseScaleOffset2(scaleOffset2) {
  7732. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET2, scaleOffset2);
  7733. }
  7734. set diffuseScaleOffset3(scaleOffset3) {
  7735. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET3, scaleOffset3);
  7736. }
  7737. set diffuseScaleOffset4(scaleOffset4) {
  7738. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET4, scaleOffset4);
  7739. }
  7740. set diffuseScaleOffset5(scaleOffset5) {
  7741. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET5, scaleOffset5);
  7742. }
  7743. get enableLighting() {
  7744. return this._enableLighting;
  7745. }
  7746. set enableLighting(value) {
  7747. if (this._enableLighting !== value) {
  7748. if (value) {
  7749. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  7750. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  7751. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  7752. }
  7753. else {
  7754. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  7755. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  7756. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  7757. }
  7758. this._enableLighting = value;
  7759. }
  7760. }
  7761. set renderMode(value) {
  7762. switch (value) {
  7763. case ExtendTerrainMaterial.RENDERMODE_OPAQUE:
  7764. this.renderQueue = BaseMaterial.RENDERQUEUE_OPAQUE;
  7765. this.depthWrite = true;
  7766. this.cull = RenderState.CULL_BACK;
  7767. this.blend = RenderState.BLEND_DISABLE;
  7768. this.depthTest = RenderState.DEPTHTEST_LESS;
  7769. break;
  7770. case ExtendTerrainMaterial.RENDERMODE_TRANSPARENT:
  7771. this.renderQueue = BaseMaterial.RENDERQUEUE_OPAQUE;
  7772. this.depthWrite = false;
  7773. this.cull = RenderState.CULL_BACK;
  7774. this.blend = RenderState.BLEND_ENABLE_ALL;
  7775. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  7776. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  7777. this.depthTest = RenderState.DEPTHTEST_LEQUAL;
  7778. break;
  7779. default:
  7780. throw new Error("ExtendTerrainMaterial:renderMode value error.");
  7781. }
  7782. }
  7783. set depthWrite(value) {
  7784. this._shaderValues.setBool(ExtendTerrainMaterial.DEPTH_WRITE, value);
  7785. }
  7786. get depthWrite() {
  7787. return this._shaderValues.getBool(ExtendTerrainMaterial.DEPTH_WRITE);
  7788. }
  7789. set cull(value) {
  7790. this._shaderValues.setInt(ExtendTerrainMaterial.CULL, value);
  7791. }
  7792. get cull() {
  7793. return this._shaderValues.getInt(ExtendTerrainMaterial.CULL);
  7794. }
  7795. set blend(value) {
  7796. this._shaderValues.setInt(ExtendTerrainMaterial.BLEND, value);
  7797. }
  7798. get blend() {
  7799. return this._shaderValues.getInt(ExtendTerrainMaterial.BLEND);
  7800. }
  7801. set blendSrc(value) {
  7802. this._shaderValues.setInt(ExtendTerrainMaterial.BLEND_SRC, value);
  7803. }
  7804. get blendSrc() {
  7805. return this._shaderValues.getInt(ExtendTerrainMaterial.BLEND_SRC);
  7806. }
  7807. set blendDst(value) {
  7808. this._shaderValues.setInt(ExtendTerrainMaterial.BLEND_DST, value);
  7809. }
  7810. get blendDst() {
  7811. return this._shaderValues.getInt(ExtendTerrainMaterial.BLEND_DST);
  7812. }
  7813. set depthTest(value) {
  7814. this._shaderValues.setInt(ExtendTerrainMaterial.DEPTH_TEST, value);
  7815. }
  7816. get depthTest() {
  7817. return this._shaderValues.getInt(ExtendTerrainMaterial.DEPTH_TEST);
  7818. }
  7819. clone() {
  7820. var dest = new ExtendTerrainMaterial();
  7821. this.cloneTo(dest);
  7822. return dest;
  7823. }
  7824. }
  7825. ExtendTerrainMaterial.RENDERMODE_OPAQUE = 1;
  7826. ExtendTerrainMaterial.RENDERMODE_TRANSPARENT = 2;
  7827. ExtendTerrainMaterial.SPLATALPHATEXTURE = Shader3D.propertyNameToID("u_SplatAlphaTexture");
  7828. ExtendTerrainMaterial.DIFFUSETEXTURE1 = Shader3D.propertyNameToID("u_DiffuseTexture1");
  7829. ExtendTerrainMaterial.DIFFUSETEXTURE2 = Shader3D.propertyNameToID("u_DiffuseTexture2");
  7830. ExtendTerrainMaterial.DIFFUSETEXTURE3 = Shader3D.propertyNameToID("u_DiffuseTexture3");
  7831. ExtendTerrainMaterial.DIFFUSETEXTURE4 = Shader3D.propertyNameToID("u_DiffuseTexture4");
  7832. ExtendTerrainMaterial.DIFFUSETEXTURE5 = Shader3D.propertyNameToID("u_DiffuseTexture5");
  7833. ExtendTerrainMaterial.DIFFUSESCALEOFFSET1 = Shader3D.propertyNameToID("u_DiffuseScaleOffset1");
  7834. ExtendTerrainMaterial.DIFFUSESCALEOFFSET2 = Shader3D.propertyNameToID("u_DiffuseScaleOffset2");
  7835. ExtendTerrainMaterial.DIFFUSESCALEOFFSET3 = Shader3D.propertyNameToID("u_DiffuseScaleOffset3");
  7836. ExtendTerrainMaterial.DIFFUSESCALEOFFSET4 = Shader3D.propertyNameToID("u_DiffuseScaleOffset4");
  7837. ExtendTerrainMaterial.DIFFUSESCALEOFFSET5 = Shader3D.propertyNameToID("u_DiffuseScaleOffset5");
  7838. ExtendTerrainMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  7839. ExtendTerrainMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  7840. ExtendTerrainMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  7841. ExtendTerrainMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  7842. ExtendTerrainMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  7843. ExtendTerrainMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  7844. class PBRSpecularMaterial extends BaseMaterial {
  7845. constructor() {
  7846. super();
  7847. this.setShaderName("PBRSpecular");
  7848. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  7849. this._shaderValues.setVector(PBRSpecularMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  7850. this._emissionColor = new Vector4(0.0, 0.0, 0.0, 0.0);
  7851. this._shaderValues.setVector(PBRSpecularMaterial.EMISSIONCOLOR, new Vector4(0.0, 0.0, 0.0, 0.0));
  7852. this._specularColor = new Vector4(0.2, 0.2, 0.2, 0.2);
  7853. this._shaderValues.setVector(PBRSpecularMaterial.SPECULARCOLOR, new Vector4(0.2, 0.2, 0.2, 0.2));
  7854. this._shaderValues.setNumber(PBRSpecularMaterial.SMOOTHNESS, 0.5);
  7855. this._shaderValues.setNumber(PBRSpecularMaterial.SMOOTHNESSSCALE, 1.0);
  7856. this._shaderValues.setNumber(PBRSpecularMaterial.SMOOTHNESSSOURCE, 0);
  7857. this._shaderValues.setNumber(PBRSpecularMaterial.OCCLUSIONSTRENGTH, 1.0);
  7858. this._shaderValues.setNumber(PBRSpecularMaterial.NORMALSCALE, 1.0);
  7859. this._shaderValues.setNumber(PBRSpecularMaterial.PARALLAXSCALE, 0.001);
  7860. this._shaderValues.setBool(PBRSpecularMaterial.ENABLEEMISSION, false);
  7861. this._shaderValues.setNumber(BaseMaterial.ALPHATESTVALUE, 0.5);
  7862. this.renderMode = PBRSpecularMaterial.RENDERMODE_OPAQUE;
  7863. }
  7864. static __initDefine__() {
  7865. PBRSpecularMaterial.SHADERDEFINE_ALBEDOTEXTURE = Shader3D.getDefineByName("ALBEDOTEXTURE");
  7866. PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE = Shader3D.getDefineByName("SPECULARTEXTURE");
  7867. PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA = Shader3D.getDefineByName("SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA");
  7868. PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE = Shader3D.getDefineByName("NORMALTEXTURE");
  7869. PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE = Shader3D.getDefineByName("PARALLAXTEXTURE");
  7870. PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE = Shader3D.getDefineByName("OCCLUSIONTEXTURE");
  7871. PBRSpecularMaterial.SHADERDEFINE_EMISSION = Shader3D.getDefineByName("EMISSION");
  7872. PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE = Shader3D.getDefineByName("EMISSIONTEXTURE");
  7873. PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  7874. PBRSpecularMaterial.SHADERDEFINE_ALPHAPREMULTIPLY = Shader3D.getDefineByName("ALPHAPREMULTIPLY");
  7875. }
  7876. get _ColorR() {
  7877. return this._albedoColor.x;
  7878. }
  7879. set _ColorR(value) {
  7880. this._albedoColor.x = value;
  7881. this.albedoColor = this._albedoColor;
  7882. }
  7883. get _ColorG() {
  7884. return this._albedoColor.y;
  7885. }
  7886. set _ColorG(value) {
  7887. this._albedoColor.y = value;
  7888. this.albedoColor = this._albedoColor;
  7889. }
  7890. get _ColorB() {
  7891. return this._albedoColor.z;
  7892. }
  7893. set _ColorB(value) {
  7894. this._albedoColor.z = value;
  7895. this.albedoColor = this._albedoColor;
  7896. }
  7897. get _ColorA() {
  7898. return this._albedoColor.w;
  7899. }
  7900. set _ColorA(value) {
  7901. this._albedoColor.w = value;
  7902. this.albedoColor = this._albedoColor;
  7903. }
  7904. get _SpecColorR() {
  7905. return this._specularColor.x;
  7906. }
  7907. set _SpecColorR(value) {
  7908. this._specularColor.x = value;
  7909. this.specularColor = this._specularColor;
  7910. }
  7911. get _SpecColorG() {
  7912. return this._specularColor.y;
  7913. }
  7914. set _SpecColorG(value) {
  7915. this._specularColor.y = value;
  7916. this.specularColor = this._specularColor;
  7917. }
  7918. get _SpecColorB() {
  7919. return this._specularColor.z;
  7920. }
  7921. set _SpecColorB(value) {
  7922. this._specularColor.z = value;
  7923. this.specularColor = this._specularColor;
  7924. }
  7925. get _SpecColorA() {
  7926. return this._specularColor.w;
  7927. }
  7928. set _SpecColorA(value) {
  7929. this._specularColor.w = value;
  7930. this.specularColor = this._specularColor;
  7931. }
  7932. get _Glossiness() {
  7933. return this._shaderValues.getNumber(PBRSpecularMaterial.SMOOTHNESS);
  7934. }
  7935. set _Glossiness(value) {
  7936. this._shaderValues.setNumber(PBRSpecularMaterial.SMOOTHNESS, value);
  7937. }
  7938. get _GlossMapScale() {
  7939. return this._shaderValues.getNumber(PBRSpecularMaterial.SMOOTHNESSSCALE);
  7940. }
  7941. set _GlossMapScale(value) {
  7942. this._shaderValues.setNumber(PBRSpecularMaterial.SMOOTHNESSSCALE, value);
  7943. }
  7944. get _BumpScale() {
  7945. return this._shaderValues.getNumber(PBRSpecularMaterial.NORMALSCALE);
  7946. }
  7947. set _BumpScale(value) {
  7948. this._shaderValues.setNumber(PBRSpecularMaterial.NORMALSCALE, value);
  7949. }
  7950. get _Parallax() {
  7951. return this._shaderValues.getNumber(PBRSpecularMaterial.PARALLAXSCALE);
  7952. }
  7953. set _Parallax(value) {
  7954. this._shaderValues.setNumber(PBRSpecularMaterial.PARALLAXSCALE, value);
  7955. }
  7956. get _OcclusionStrength() {
  7957. return this._shaderValues.getNumber(PBRSpecularMaterial.OCCLUSIONSTRENGTH);
  7958. }
  7959. set _OcclusionStrength(value) {
  7960. this._shaderValues.setNumber(PBRSpecularMaterial.OCCLUSIONSTRENGTH, value);
  7961. }
  7962. get _EmissionColorR() {
  7963. return this._emissionColor.x;
  7964. }
  7965. set _EmissionColorR(value) {
  7966. this._emissionColor.x = value;
  7967. this.emissionColor = this._emissionColor;
  7968. }
  7969. get _EmissionColorG() {
  7970. return this._emissionColor.y;
  7971. }
  7972. set _EmissionColorG(value) {
  7973. this._emissionColor.y = value;
  7974. this.emissionColor = this._emissionColor;
  7975. }
  7976. get _EmissionColorB() {
  7977. return this._emissionColor.z;
  7978. }
  7979. set _EmissionColorB(value) {
  7980. this._emissionColor.z = value;
  7981. this.emissionColor = this._emissionColor;
  7982. }
  7983. get _EmissionColorA() {
  7984. return this._emissionColor.w;
  7985. }
  7986. set _EmissionColorA(value) {
  7987. this._emissionColor.w = value;
  7988. this.emissionColor = this._emissionColor;
  7989. }
  7990. get _MainTex_STX() {
  7991. return this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET).x;
  7992. }
  7993. set _MainTex_STX(x) {
  7994. var tilOff = this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET);
  7995. tilOff.x = x;
  7996. this.tilingOffset = tilOff;
  7997. }
  7998. get _MainTex_STY() {
  7999. return this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET).y;
  8000. }
  8001. set _MainTex_STY(y) {
  8002. var tilOff = this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET);
  8003. tilOff.y = y;
  8004. this.tilingOffset = tilOff;
  8005. }
  8006. get _MainTex_STZ() {
  8007. return this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET).z;
  8008. }
  8009. set _MainTex_STZ(z) {
  8010. var tilOff = this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET);
  8011. tilOff.z = z;
  8012. this.tilingOffset = tilOff;
  8013. }
  8014. get _MainTex_STW() {
  8015. return this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET).w;
  8016. }
  8017. set _MainTex_STW(w) {
  8018. var tilOff = this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET);
  8019. tilOff.w = w;
  8020. this.tilingOffset = tilOff;
  8021. }
  8022. get _Cutoff() {
  8023. return this.alphaTestValue;
  8024. }
  8025. set _Cutoff(value) {
  8026. this.alphaTestValue = value;
  8027. }
  8028. get albedoColorR() {
  8029. return this._ColorR;
  8030. }
  8031. set albedoColorR(value) {
  8032. this._ColorR = value;
  8033. }
  8034. get albedoColorG() {
  8035. return this._ColorG;
  8036. }
  8037. set albedoColorG(value) {
  8038. this._ColorG = value;
  8039. }
  8040. get albedoColorB() {
  8041. return this._ColorB;
  8042. }
  8043. set albedoColorB(value) {
  8044. this._ColorB = value;
  8045. }
  8046. get albedoColorA() {
  8047. return this._ColorA;
  8048. }
  8049. set albedoColorA(value) {
  8050. this._ColorA = value;
  8051. }
  8052. get albedoColor() {
  8053. return this._albedoColor;
  8054. }
  8055. set albedoColor(value) {
  8056. this._albedoColor = value;
  8057. this._shaderValues.setVector(PBRSpecularMaterial.ALBEDOCOLOR, value);
  8058. }
  8059. get albedoTexture() {
  8060. return this._shaderValues.getTexture(PBRSpecularMaterial.ALBEDOTEXTURE);
  8061. }
  8062. set albedoTexture(value) {
  8063. if (value) {
  8064. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  8065. }
  8066. else {
  8067. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  8068. }
  8069. this._shaderValues.setTexture(PBRSpecularMaterial.ALBEDOTEXTURE, value);
  8070. }
  8071. get normalTexture() {
  8072. return this._shaderValues.getTexture(PBRSpecularMaterial.NORMALTEXTURE);
  8073. }
  8074. set normalTexture(value) {
  8075. if (value) {
  8076. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE);
  8077. }
  8078. else {
  8079. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE);
  8080. }
  8081. this._shaderValues.setTexture(PBRSpecularMaterial.NORMALTEXTURE, value);
  8082. }
  8083. get normalTextureScale() {
  8084. return this._BumpScale;
  8085. }
  8086. set normalTextureScale(value) {
  8087. this._BumpScale = value;
  8088. }
  8089. get parallaxTexture() {
  8090. return this._shaderValues.getTexture(PBRSpecularMaterial.PARALLAXTEXTURE);
  8091. }
  8092. set parallaxTexture(value) {
  8093. if (value) {
  8094. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  8095. }
  8096. else {
  8097. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  8098. }
  8099. this._shaderValues.setTexture(PBRSpecularMaterial.PARALLAXTEXTURE, value);
  8100. }
  8101. get parallaxTextureScale() {
  8102. return this._Parallax;
  8103. }
  8104. set parallaxTextureScale(value) {
  8105. this._Parallax = Math.max(0.005, Math.min(0.08, value));
  8106. }
  8107. get occlusionTexture() {
  8108. return this._shaderValues.getTexture(PBRSpecularMaterial.OCCLUSIONTEXTURE);
  8109. }
  8110. set occlusionTexture(value) {
  8111. if (value) {
  8112. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  8113. }
  8114. else {
  8115. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  8116. }
  8117. this._shaderValues.setTexture(PBRSpecularMaterial.OCCLUSIONTEXTURE, value);
  8118. }
  8119. get occlusionTextureStrength() {
  8120. return this._OcclusionStrength;
  8121. }
  8122. set occlusionTextureStrength(value) {
  8123. this._OcclusionStrength = Math.max(0.0, Math.min(1.0, value));
  8124. }
  8125. get specularTexture() {
  8126. return this._shaderValues.getTexture(PBRSpecularMaterial.SPECULARTEXTURE);
  8127. }
  8128. set specularTexture(value) {
  8129. if (value) {
  8130. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE);
  8131. }
  8132. else {
  8133. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE);
  8134. }
  8135. this._shaderValues.setTexture(PBRSpecularMaterial.SPECULARTEXTURE, value);
  8136. }
  8137. get specularColorR() {
  8138. return this._SpecColorR;
  8139. }
  8140. set specularColorR(value) {
  8141. this._SpecColorR = value;
  8142. }
  8143. get specularColorG() {
  8144. return this._SpecColorG;
  8145. }
  8146. set specularColorG(value) {
  8147. this._SpecColorG = value;
  8148. }
  8149. get specularColorB() {
  8150. return this._SpecColorB;
  8151. }
  8152. set specularColorB(value) {
  8153. this._SpecColorB = value;
  8154. }
  8155. get specularColorA() {
  8156. return this._SpecColorA;
  8157. }
  8158. set specularColorA(value) {
  8159. this._SpecColorA = value;
  8160. }
  8161. get specularColor() {
  8162. return this._shaderValues.getVector(PBRSpecularMaterial.SPECULARCOLOR);
  8163. }
  8164. set specularColor(value) {
  8165. this._shaderValues.setVector(PBRSpecularMaterial.SPECULARCOLOR, value);
  8166. }
  8167. get smoothness() {
  8168. return this._Glossiness;
  8169. }
  8170. set smoothness(value) {
  8171. this._Glossiness = Math.max(0.0, Math.min(1.0, value));
  8172. }
  8173. get smoothnessTextureScale() {
  8174. return this._GlossMapScale;
  8175. }
  8176. set smoothnessTextureScale(value) {
  8177. this._GlossMapScale = Math.max(0.0, Math.min(1.0, value));
  8178. }
  8179. get smoothnessSource() {
  8180. return this._shaderValues.getInt(PBRSpecularMaterial.SMOOTHNESSSOURCE);
  8181. }
  8182. set smoothnessSource(value) {
  8183. if (value) {
  8184. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  8185. this._shaderValues.setInt(PBRSpecularMaterial.SMOOTHNESSSOURCE, 1);
  8186. }
  8187. else {
  8188. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  8189. this._shaderValues.setInt(PBRSpecularMaterial.SMOOTHNESSSOURCE, 0);
  8190. }
  8191. }
  8192. get enableEmission() {
  8193. return this._shaderValues.getBool(PBRSpecularMaterial.ENABLEEMISSION);
  8194. }
  8195. set enableEmission(value) {
  8196. if (value)
  8197. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_EMISSION);
  8198. else {
  8199. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_EMISSION);
  8200. }
  8201. this._shaderValues.setBool(PBRSpecularMaterial.ENABLEEMISSION, value);
  8202. }
  8203. get emissionColor() {
  8204. return this._shaderValues.getVector(PBRSpecularMaterial.EMISSIONCOLOR);
  8205. }
  8206. set emissionColor(value) {
  8207. this._shaderValues.setVector(PBRSpecularMaterial.EMISSIONCOLOR, value);
  8208. }
  8209. get emissionTexture() {
  8210. return this._shaderValues.getTexture(PBRSpecularMaterial.EMISSIONTEXTURE);
  8211. }
  8212. set emissionTexture(value) {
  8213. if (value)
  8214. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  8215. else
  8216. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  8217. this._shaderValues.setTexture(PBRSpecularMaterial.EMISSIONTEXTURE, value);
  8218. }
  8219. get enableReflection() {
  8220. return this._shaderValues.getBool(PBRSpecularMaterial.ENABLEREFLECT);
  8221. }
  8222. set enableReflection(value) {
  8223. this._shaderValues.setBool(PBRSpecularMaterial.ENABLEREFLECT, true);
  8224. if (value)
  8225. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  8226. else
  8227. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  8228. }
  8229. get tilingOffsetX() {
  8230. return this._MainTex_STX;
  8231. }
  8232. set tilingOffsetX(x) {
  8233. this._MainTex_STX = x;
  8234. }
  8235. get tilingOffsetY() {
  8236. return this._MainTex_STY;
  8237. }
  8238. set tilingOffsetY(y) {
  8239. this._MainTex_STY = y;
  8240. }
  8241. get tilingOffsetZ() {
  8242. return this._MainTex_STZ;
  8243. }
  8244. set tilingOffsetZ(z) {
  8245. this._MainTex_STZ = z;
  8246. }
  8247. get tilingOffsetW() {
  8248. return this._MainTex_STW;
  8249. }
  8250. set tilingOffsetW(w) {
  8251. this._MainTex_STW = w;
  8252. }
  8253. get tilingOffset() {
  8254. return this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET);
  8255. }
  8256. set tilingOffset(value) {
  8257. if (value) {
  8258. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  8259. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET);
  8260. else
  8261. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET);
  8262. }
  8263. else {
  8264. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET);
  8265. }
  8266. this._shaderValues.setVector(PBRSpecularMaterial.TILINGOFFSET, value);
  8267. }
  8268. set renderMode(value) {
  8269. switch (value) {
  8270. case PBRSpecularMaterial.RENDERMODE_OPAQUE:
  8271. this.alphaTest = false;
  8272. this.renderQueue = BaseMaterial.RENDERQUEUE_OPAQUE;
  8273. this.depthWrite = true;
  8274. this.cull = RenderState.CULL_BACK;
  8275. this.blend = RenderState.BLEND_DISABLE;
  8276. this.depthTest = RenderState.DEPTHTEST_LESS;
  8277. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8278. break;
  8279. case PBRSpecularMaterial.RENDERMODE_CUTOUT:
  8280. this.renderQueue = BaseMaterial.RENDERQUEUE_ALPHATEST;
  8281. this.alphaTest = true;
  8282. this.depthWrite = true;
  8283. this.cull = RenderState.CULL_BACK;
  8284. this.blend = RenderState.BLEND_DISABLE;
  8285. this.depthTest = RenderState.DEPTHTEST_LESS;
  8286. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8287. break;
  8288. case PBRSpecularMaterial.RENDERMODE_FADE:
  8289. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  8290. this.alphaTest = false;
  8291. this.depthWrite = false;
  8292. this.cull = RenderState.CULL_BACK;
  8293. this.blend = RenderState.BLEND_ENABLE_ALL;
  8294. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  8295. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  8296. this.depthTest = RenderState.DEPTHTEST_LESS;
  8297. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8298. break;
  8299. case PBRSpecularMaterial.RENDERMODE_TRANSPARENT:
  8300. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  8301. this.alphaTest = false;
  8302. this.depthWrite = false;
  8303. this.cull = RenderState.CULL_BACK;
  8304. this.blend = RenderState.BLEND_ENABLE_ALL;
  8305. this.blendSrc = RenderState.BLENDPARAM_ONE;
  8306. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  8307. this.depthTest = RenderState.DEPTHTEST_LESS;
  8308. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8309. break;
  8310. default:
  8311. throw new Error("PBRSpecularMaterial : renderMode value error.");
  8312. }
  8313. }
  8314. get depthWrite() {
  8315. return this._shaderValues.getBool(PBRSpecularMaterial.DEPTH_WRITE);
  8316. }
  8317. set depthWrite(value) {
  8318. this._shaderValues.setBool(PBRSpecularMaterial.DEPTH_WRITE, value);
  8319. }
  8320. get cull() {
  8321. return this._shaderValues.getInt(PBRSpecularMaterial.CULL);
  8322. }
  8323. set cull(value) {
  8324. this._shaderValues.setInt(PBRSpecularMaterial.CULL, value);
  8325. }
  8326. get blend() {
  8327. return this._shaderValues.getInt(PBRSpecularMaterial.BLEND);
  8328. }
  8329. set blend(value) {
  8330. this._shaderValues.setInt(PBRSpecularMaterial.BLEND, value);
  8331. }
  8332. get blendSrc() {
  8333. return this._shaderValues.getInt(PBRSpecularMaterial.BLEND_SRC);
  8334. }
  8335. set blendSrc(value) {
  8336. this._shaderValues.setInt(PBRSpecularMaterial.BLEND_SRC, value);
  8337. }
  8338. get blendDst() {
  8339. return this._shaderValues.getInt(PBRSpecularMaterial.BLEND_DST);
  8340. }
  8341. set blendDst(value) {
  8342. this._shaderValues.setInt(PBRSpecularMaterial.BLEND_DST, value);
  8343. }
  8344. get depthTest() {
  8345. return this._shaderValues.getInt(PBRSpecularMaterial.DEPTH_TEST);
  8346. }
  8347. set depthTest(value) {
  8348. this._shaderValues.setInt(PBRSpecularMaterial.DEPTH_TEST, value);
  8349. }
  8350. clone() {
  8351. var dest = new PBRSpecularMaterial();
  8352. this.cloneTo(dest);
  8353. return dest;
  8354. }
  8355. cloneTo(destObject) {
  8356. super.cloneTo(destObject);
  8357. var destMaterial = destObject;
  8358. this._albedoColor.cloneTo(destMaterial._albedoColor);
  8359. this._specularColor.cloneTo(destMaterial._specularColor);
  8360. this._emissionColor.cloneTo(destMaterial._emissionColor);
  8361. }
  8362. }
  8363. PBRSpecularMaterial.SmoothnessSource_SpecularTexture_Alpha = 0;
  8364. PBRSpecularMaterial.SmoothnessSource_AlbedoTexture_Alpha = 1;
  8365. PBRSpecularMaterial.RENDERMODE_OPAQUE = 0;
  8366. PBRSpecularMaterial.RENDERMODE_CUTOUT = 1;
  8367. PBRSpecularMaterial.RENDERMODE_FADE = 2;
  8368. PBRSpecularMaterial.RENDERMODE_TRANSPARENT = 3;
  8369. PBRSpecularMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  8370. PBRSpecularMaterial.SPECULARTEXTURE = Shader3D.propertyNameToID("u_SpecularTexture");
  8371. PBRSpecularMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  8372. PBRSpecularMaterial.PARALLAXTEXTURE = Shader3D.propertyNameToID("u_ParallaxTexture");
  8373. PBRSpecularMaterial.OCCLUSIONTEXTURE = Shader3D.propertyNameToID("u_OcclusionTexture");
  8374. PBRSpecularMaterial.EMISSIONTEXTURE = Shader3D.propertyNameToID("u_EmissionTexture");
  8375. PBRSpecularMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  8376. PBRSpecularMaterial.SPECULARCOLOR = Shader3D.propertyNameToID("u_SpecularColor");
  8377. PBRSpecularMaterial.EMISSIONCOLOR = Shader3D.propertyNameToID("u_EmissionColor");
  8378. PBRSpecularMaterial.SMOOTHNESS = Shader3D.propertyNameToID("u_smoothness");
  8379. PBRSpecularMaterial.SMOOTHNESSSCALE = Shader3D.propertyNameToID("u_smoothnessScale");
  8380. PBRSpecularMaterial.SMOOTHNESSSOURCE = -1;
  8381. PBRSpecularMaterial.OCCLUSIONSTRENGTH = Shader3D.propertyNameToID("u_occlusionStrength");
  8382. PBRSpecularMaterial.NORMALSCALE = Shader3D.propertyNameToID("u_normalScale");
  8383. PBRSpecularMaterial.PARALLAXSCALE = Shader3D.propertyNameToID("u_parallaxScale");
  8384. PBRSpecularMaterial.ENABLEEMISSION = -1;
  8385. PBRSpecularMaterial.ENABLEREFLECT = -1;
  8386. PBRSpecularMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  8387. PBRSpecularMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  8388. PBRSpecularMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  8389. PBRSpecularMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  8390. PBRSpecularMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  8391. PBRSpecularMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  8392. PBRSpecularMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  8393. class PBRStandardMaterial extends BaseMaterial {
  8394. constructor() {
  8395. super();
  8396. this.setShaderName("PBRStandard");
  8397. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  8398. this._shaderValues.setVector(PBRStandardMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  8399. this._emissionColor = new Vector4(0.0, 0.0, 0.0, 0.0);
  8400. this._shaderValues.setVector(PBRStandardMaterial.EMISSIONCOLOR, new Vector4(0.0, 0.0, 0.0, 0.0));
  8401. this._shaderValues.setNumber(PBRStandardMaterial.METALLIC, 0.0);
  8402. this._shaderValues.setNumber(PBRStandardMaterial.SMOOTHNESS, 0.5);
  8403. this._shaderValues.setNumber(PBRStandardMaterial.SMOOTHNESSSCALE, 1.0);
  8404. this._shaderValues.setNumber(PBRStandardMaterial.SMOOTHNESSSOURCE, 0);
  8405. this._shaderValues.setNumber(PBRStandardMaterial.OCCLUSIONSTRENGTH, 1.0);
  8406. this._shaderValues.setNumber(PBRStandardMaterial.NORMALSCALE, 1.0);
  8407. this._shaderValues.setNumber(PBRStandardMaterial.PARALLAXSCALE, 0.001);
  8408. this._shaderValues.setBool(PBRStandardMaterial.ENABLEEMISSION, false);
  8409. this._shaderValues.setBool(PBRStandardMaterial.ENABLEREFLECT, true);
  8410. this._shaderValues.setNumber(BaseMaterial.ALPHATESTVALUE, 0.5);
  8411. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  8412. this.renderMode = PBRStandardMaterial.RENDERMODE_OPAQUE;
  8413. }
  8414. static __initDefine__() {
  8415. PBRStandardMaterial.SHADERDEFINE_ALBEDOTEXTURE = Shader3D.getDefineByName("ALBEDOTEXTURE");
  8416. PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE = Shader3D.getDefineByName("METALLICGLOSSTEXTURE");
  8417. PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA = Shader3D.getDefineByName("SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA");
  8418. PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE = Shader3D.getDefineByName("NORMALTEXTURE");
  8419. PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE = Shader3D.getDefineByName("PARALLAXTEXTURE");
  8420. PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE = Shader3D.getDefineByName("OCCLUSIONTEXTURE");
  8421. PBRStandardMaterial.SHADERDEFINE_EMISSION = Shader3D.getDefineByName("EMISSION");
  8422. PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE = Shader3D.getDefineByName("EMISSIONTEXTURE");
  8423. PBRStandardMaterial.SHADERDEFINE_REFLECTMAP = Shader3D.getDefineByName("REFLECTMAP");
  8424. PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  8425. PBRStandardMaterial.SHADERDEFINE_ALPHAPREMULTIPLY = Shader3D.getDefineByName("ALPHAPREMULTIPLY");
  8426. }
  8427. get _ColorR() {
  8428. return this._albedoColor.x;
  8429. }
  8430. set _ColorR(value) {
  8431. this._albedoColor.x = value;
  8432. this.albedoColor = this._albedoColor;
  8433. }
  8434. get _ColorG() {
  8435. return this._albedoColor.y;
  8436. }
  8437. set _ColorG(value) {
  8438. this._albedoColor.y = value;
  8439. this.albedoColor = this._albedoColor;
  8440. }
  8441. get _ColorB() {
  8442. return this._albedoColor.z;
  8443. }
  8444. set _ColorB(value) {
  8445. this._albedoColor.z = value;
  8446. this.albedoColor = this._albedoColor;
  8447. }
  8448. get _ColorA() {
  8449. return this._albedoColor.w;
  8450. }
  8451. set _ColorA(value) {
  8452. this._albedoColor.w = value;
  8453. this.albedoColor = this._albedoColor;
  8454. }
  8455. get _Metallic() {
  8456. return this._shaderValues.getNumber(PBRStandardMaterial.METALLIC);
  8457. }
  8458. set _Metallic(value) {
  8459. this._shaderValues.setNumber(PBRStandardMaterial.METALLIC, value);
  8460. }
  8461. get _Glossiness() {
  8462. return this._shaderValues.getNumber(PBRStandardMaterial.SMOOTHNESS);
  8463. }
  8464. set _Glossiness(value) {
  8465. this._shaderValues.setNumber(PBRStandardMaterial.SMOOTHNESS, value);
  8466. }
  8467. get _GlossMapScale() {
  8468. return this._shaderValues.getNumber(PBRStandardMaterial.SMOOTHNESSSCALE);
  8469. }
  8470. set _GlossMapScale(value) {
  8471. this._shaderValues.setNumber(PBRStandardMaterial.SMOOTHNESSSCALE, value);
  8472. }
  8473. get _BumpScale() {
  8474. return this._shaderValues.getNumber(PBRStandardMaterial.NORMALSCALE);
  8475. }
  8476. set _BumpScale(value) {
  8477. this._shaderValues.setNumber(PBRStandardMaterial.NORMALSCALE, value);
  8478. }
  8479. get _Parallax() {
  8480. return this._shaderValues.getNumber(PBRStandardMaterial.PARALLAXSCALE);
  8481. }
  8482. set _Parallax(value) {
  8483. this._shaderValues.setNumber(PBRStandardMaterial.PARALLAXSCALE, value);
  8484. }
  8485. get _OcclusionStrength() {
  8486. return this._shaderValues.getNumber(PBRStandardMaterial.OCCLUSIONSTRENGTH);
  8487. }
  8488. set _OcclusionStrength(value) {
  8489. this._shaderValues.setNumber(PBRStandardMaterial.OCCLUSIONSTRENGTH, value);
  8490. }
  8491. get _EmissionColorR() {
  8492. return this._emissionColor.x;
  8493. }
  8494. set _EmissionColorR(value) {
  8495. this._emissionColor.x = value;
  8496. this.emissionColor = this._emissionColor;
  8497. }
  8498. get _EmissionColorG() {
  8499. return this._emissionColor.y;
  8500. }
  8501. set _EmissionColorG(value) {
  8502. this._emissionColor.y = value;
  8503. this.emissionColor = this._emissionColor;
  8504. }
  8505. get _EmissionColorB() {
  8506. return this._emissionColor.z;
  8507. }
  8508. set _EmissionColorB(value) {
  8509. this._emissionColor.z = value;
  8510. this.emissionColor = this._emissionColor;
  8511. }
  8512. get _EmissionColorA() {
  8513. return this._emissionColor.w;
  8514. }
  8515. set _EmissionColorA(value) {
  8516. this._emissionColor.w = value;
  8517. this.emissionColor = this._emissionColor;
  8518. }
  8519. get _MainTex_STX() {
  8520. return this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET).x;
  8521. }
  8522. set _MainTex_STX(x) {
  8523. var tilOff = this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET);
  8524. tilOff.x = x;
  8525. this.tilingOffset = tilOff;
  8526. }
  8527. get _MainTex_STY() {
  8528. return this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET).y;
  8529. }
  8530. set _MainTex_STY(y) {
  8531. var tilOff = this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET);
  8532. tilOff.y = y;
  8533. this.tilingOffset = tilOff;
  8534. }
  8535. get _MainTex_STZ() {
  8536. return this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET).z;
  8537. }
  8538. set _MainTex_STZ(z) {
  8539. var tilOff = this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET);
  8540. tilOff.z = z;
  8541. this.tilingOffset = tilOff;
  8542. }
  8543. get _MainTex_STW() {
  8544. return this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET).w;
  8545. }
  8546. set _MainTex_STW(w) {
  8547. var tilOff = this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET);
  8548. tilOff.w = w;
  8549. this.tilingOffset = tilOff;
  8550. }
  8551. get _Cutoff() {
  8552. return this.alphaTestValue;
  8553. }
  8554. set _Cutoff(value) {
  8555. this.alphaTestValue = value;
  8556. }
  8557. get albedoColorR() {
  8558. return this._ColorR;
  8559. }
  8560. set albedoColorR(value) {
  8561. this._ColorR = value;
  8562. }
  8563. get albedoColorG() {
  8564. return this._ColorG;
  8565. }
  8566. set albedoColorG(value) {
  8567. this._ColorG = value;
  8568. }
  8569. get albedoColorB() {
  8570. return this._ColorB;
  8571. }
  8572. set albedoColorB(value) {
  8573. this._ColorB = value;
  8574. }
  8575. get albedoColorA() {
  8576. return this._ColorA;
  8577. }
  8578. set albedoColorA(value) {
  8579. this._ColorA = value;
  8580. }
  8581. get albedoColor() {
  8582. return this._albedoColor;
  8583. }
  8584. set albedoColor(value) {
  8585. this._albedoColor = value;
  8586. this._shaderValues.setVector(PBRStandardMaterial.ALBEDOCOLOR, value);
  8587. }
  8588. get albedoTexture() {
  8589. return this._shaderValues.getTexture(PBRStandardMaterial.ALBEDOTEXTURE);
  8590. }
  8591. set albedoTexture(value) {
  8592. if (value) {
  8593. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  8594. }
  8595. else {
  8596. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  8597. }
  8598. this._shaderValues.setTexture(PBRStandardMaterial.ALBEDOTEXTURE, value);
  8599. }
  8600. get normalTexture() {
  8601. return this._shaderValues.getTexture(PBRStandardMaterial.NORMALTEXTURE);
  8602. }
  8603. set normalTexture(value) {
  8604. if (value) {
  8605. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE);
  8606. }
  8607. else {
  8608. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE);
  8609. }
  8610. this._shaderValues.setTexture(PBRStandardMaterial.NORMALTEXTURE, value);
  8611. }
  8612. get normalTextureScale() {
  8613. return this._BumpScale;
  8614. }
  8615. set normalTextureScale(value) {
  8616. this._BumpScale = value;
  8617. }
  8618. get parallaxTexture() {
  8619. return this._shaderValues.getTexture(PBRStandardMaterial.PARALLAXTEXTURE);
  8620. }
  8621. set parallaxTexture(value) {
  8622. if (value) {
  8623. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  8624. }
  8625. else {
  8626. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  8627. }
  8628. this._shaderValues.setTexture(PBRStandardMaterial.PARALLAXTEXTURE, value);
  8629. }
  8630. get parallaxTextureScale() {
  8631. return this._Parallax;
  8632. }
  8633. set parallaxTextureScale(value) {
  8634. this._Parallax = Math.max(0.005, Math.min(0.08, value));
  8635. }
  8636. get occlusionTexture() {
  8637. return this._shaderValues.getTexture(PBRStandardMaterial.OCCLUSIONTEXTURE);
  8638. }
  8639. set occlusionTexture(value) {
  8640. if (value) {
  8641. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  8642. }
  8643. else {
  8644. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  8645. }
  8646. this._shaderValues.setTexture(PBRStandardMaterial.OCCLUSIONTEXTURE, value);
  8647. }
  8648. get occlusionTextureStrength() {
  8649. return this._OcclusionStrength;
  8650. }
  8651. set occlusionTextureStrength(value) {
  8652. this._OcclusionStrength = Math.max(0.0, Math.min(1.0, value));
  8653. }
  8654. get metallicGlossTexture() {
  8655. return this._shaderValues.getTexture(PBRStandardMaterial.METALLICGLOSSTEXTURE);
  8656. }
  8657. set metallicGlossTexture(value) {
  8658. if (value) {
  8659. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE);
  8660. }
  8661. else {
  8662. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE);
  8663. }
  8664. this._shaderValues.setTexture(PBRStandardMaterial.METALLICGLOSSTEXTURE, value);
  8665. }
  8666. get metallic() {
  8667. return this._Metallic;
  8668. }
  8669. set metallic(value) {
  8670. this._Metallic = Math.max(0.0, Math.min(1.0, value));
  8671. }
  8672. get smoothness() {
  8673. return this._Glossiness;
  8674. }
  8675. set smoothness(value) {
  8676. this._Glossiness = Math.max(0.0, Math.min(1.0, value));
  8677. }
  8678. get smoothnessTextureScale() {
  8679. return this._GlossMapScale;
  8680. }
  8681. set smoothnessTextureScale(value) {
  8682. this._GlossMapScale = Math.max(0.0, Math.min(1.0, value));
  8683. }
  8684. get smoothnessSource() {
  8685. return this._shaderValues.getInt(PBRStandardMaterial.SMOOTHNESSSOURCE);
  8686. }
  8687. set smoothnessSource(value) {
  8688. if (value) {
  8689. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  8690. this._shaderValues.setInt(PBRStandardMaterial.SMOOTHNESSSOURCE, 1);
  8691. }
  8692. else {
  8693. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  8694. this._shaderValues.setInt(PBRStandardMaterial.SMOOTHNESSSOURCE, 0);
  8695. }
  8696. }
  8697. get enableEmission() {
  8698. return this._shaderValues.getBool(PBRStandardMaterial.ENABLEEMISSION);
  8699. }
  8700. set enableEmission(value) {
  8701. if (value) {
  8702. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_EMISSION);
  8703. }
  8704. else {
  8705. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_EMISSION);
  8706. }
  8707. this._shaderValues.setBool(PBRStandardMaterial.ENABLEEMISSION, value);
  8708. }
  8709. get emissionColorR() {
  8710. return this._EmissionColorR;
  8711. }
  8712. set emissionColorR(value) {
  8713. this._EmissionColorR = value;
  8714. }
  8715. get emissionColorG() {
  8716. return this._EmissionColorG;
  8717. }
  8718. set emissionColorG(value) {
  8719. this._EmissionColorG = value;
  8720. }
  8721. get emissionColorB() {
  8722. return this._EmissionColorB;
  8723. }
  8724. set emissionColorB(value) {
  8725. this._EmissionColorB = value;
  8726. }
  8727. get emissionColorA() {
  8728. return this._EmissionColorA;
  8729. }
  8730. set emissionColorA(value) {
  8731. this._EmissionColorA = value;
  8732. }
  8733. get emissionColor() {
  8734. return this._shaderValues.getVector(PBRStandardMaterial.EMISSIONCOLOR);
  8735. }
  8736. set emissionColor(value) {
  8737. this._shaderValues.setVector(PBRStandardMaterial.EMISSIONCOLOR, value);
  8738. }
  8739. get emissionTexture() {
  8740. return this._shaderValues.getTexture(PBRStandardMaterial.EMISSIONTEXTURE);
  8741. }
  8742. set emissionTexture(value) {
  8743. if (value) {
  8744. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  8745. }
  8746. else {
  8747. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  8748. }
  8749. this._shaderValues.setTexture(PBRStandardMaterial.EMISSIONTEXTURE, value);
  8750. }
  8751. get enableReflection() {
  8752. return this._shaderValues.getBool(PBRStandardMaterial.ENABLEREFLECT);
  8753. }
  8754. set enableReflection(value) {
  8755. this._shaderValues.setBool(PBRStandardMaterial.ENABLEREFLECT, true);
  8756. if (value) {
  8757. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  8758. }
  8759. else {
  8760. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  8761. }
  8762. }
  8763. get tilingOffsetX() {
  8764. return this._MainTex_STX;
  8765. }
  8766. set tilingOffsetX(x) {
  8767. this._MainTex_STX = x;
  8768. }
  8769. get tilingOffsetY() {
  8770. return this._MainTex_STY;
  8771. }
  8772. set tilingOffsetY(y) {
  8773. this._MainTex_STY = y;
  8774. }
  8775. get tilingOffsetZ() {
  8776. return this._MainTex_STZ;
  8777. }
  8778. set tilingOffsetZ(z) {
  8779. this._MainTex_STZ = z;
  8780. }
  8781. get tilingOffsetW() {
  8782. return this._MainTex_STW;
  8783. }
  8784. set tilingOffsetW(w) {
  8785. this._MainTex_STW = w;
  8786. }
  8787. get tilingOffset() {
  8788. return this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET);
  8789. }
  8790. set tilingOffset(value) {
  8791. if (value) {
  8792. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0) {
  8793. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET);
  8794. }
  8795. else {
  8796. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET);
  8797. }
  8798. }
  8799. else {
  8800. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET);
  8801. }
  8802. this._shaderValues.setVector(PBRStandardMaterial.TILINGOFFSET, value);
  8803. }
  8804. set renderMode(value) {
  8805. switch (value) {
  8806. case PBRStandardMaterial.RENDERMODE_OPAQUE:
  8807. this.alphaTest = false;
  8808. this.renderQueue = BaseMaterial.RENDERQUEUE_OPAQUE;
  8809. this.depthWrite = true;
  8810. this.cull = RenderState.CULL_BACK;
  8811. this.blend = RenderState.BLEND_DISABLE;
  8812. this.depthTest = RenderState.DEPTHTEST_LESS;
  8813. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8814. break;
  8815. case PBRStandardMaterial.RENDERMODE_CUTOUT:
  8816. this.renderQueue = BaseMaterial.RENDERQUEUE_ALPHATEST;
  8817. this.alphaTest = true;
  8818. this.depthWrite = true;
  8819. this.cull = RenderState.CULL_BACK;
  8820. this.blend = RenderState.BLEND_DISABLE;
  8821. this.depthTest = RenderState.DEPTHTEST_LESS;
  8822. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8823. break;
  8824. case PBRStandardMaterial.RENDERMODE_FADE:
  8825. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  8826. this.alphaTest = false;
  8827. this.depthWrite = false;
  8828. this.cull = RenderState.CULL_BACK;
  8829. this.blend = RenderState.BLEND_ENABLE_ALL;
  8830. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  8831. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  8832. this.depthTest = RenderState.DEPTHTEST_LESS;
  8833. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8834. break;
  8835. break;
  8836. case PBRStandardMaterial.RENDERMODE_TRANSPARENT:
  8837. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  8838. this.alphaTest = false;
  8839. this.depthWrite = false;
  8840. this.cull = RenderState.CULL_BACK;
  8841. this.blend = RenderState.BLEND_ENABLE_ALL;
  8842. this.blendSrc = RenderState.BLENDPARAM_ONE;
  8843. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  8844. this.depthTest = RenderState.DEPTHTEST_LESS;
  8845. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8846. break;
  8847. default:
  8848. throw new Error("PBRSpecularMaterial : renderMode value error.");
  8849. }
  8850. }
  8851. get depthWrite() {
  8852. return this._shaderValues.getBool(PBRStandardMaterial.DEPTH_WRITE);
  8853. }
  8854. set depthWrite(value) {
  8855. this._shaderValues.setBool(PBRStandardMaterial.DEPTH_WRITE, value);
  8856. }
  8857. get cull() {
  8858. return this._shaderValues.getInt(PBRStandardMaterial.CULL);
  8859. }
  8860. set cull(value) {
  8861. this._shaderValues.setInt(PBRStandardMaterial.CULL, value);
  8862. }
  8863. get blend() {
  8864. return this._shaderValues.getInt(PBRStandardMaterial.BLEND);
  8865. }
  8866. set blend(value) {
  8867. this._shaderValues.setInt(PBRStandardMaterial.BLEND, value);
  8868. }
  8869. get blendSrc() {
  8870. return this._shaderValues.getInt(PBRStandardMaterial.BLEND_SRC);
  8871. }
  8872. set blendSrc(value) {
  8873. this._shaderValues.setInt(PBRStandardMaterial.BLEND_SRC, value);
  8874. }
  8875. get blendDst() {
  8876. return this._shaderValues.getInt(PBRStandardMaterial.BLEND_DST);
  8877. }
  8878. set blendDst(value) {
  8879. this._shaderValues.setInt(PBRStandardMaterial.BLEND_DST, value);
  8880. }
  8881. get depthTest() {
  8882. return this._shaderValues.getInt(PBRStandardMaterial.DEPTH_TEST);
  8883. }
  8884. set depthTest(value) {
  8885. this._shaderValues.setInt(PBRStandardMaterial.DEPTH_TEST, value);
  8886. }
  8887. clone() {
  8888. var dest = new PBRStandardMaterial();
  8889. this.cloneTo(dest);
  8890. return dest;
  8891. }
  8892. cloneTo(destObject) {
  8893. super.cloneTo(destObject);
  8894. var destMaterial = destObject;
  8895. this._albedoColor.cloneTo(destMaterial._albedoColor);
  8896. this._emissionColor.cloneTo(destMaterial._emissionColor);
  8897. }
  8898. }
  8899. PBRStandardMaterial.SmoothnessSource_MetallicGlossTexture_Alpha = 0;
  8900. PBRStandardMaterial.SmoothnessSource_AlbedoTexture_Alpha = 1;
  8901. PBRStandardMaterial.RENDERMODE_OPAQUE = 0;
  8902. PBRStandardMaterial.RENDERMODE_CUTOUT = 1;
  8903. PBRStandardMaterial.RENDERMODE_FADE = 2;
  8904. PBRStandardMaterial.RENDERMODE_TRANSPARENT = 3;
  8905. PBRStandardMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  8906. PBRStandardMaterial.METALLICGLOSSTEXTURE = Shader3D.propertyNameToID("u_MetallicGlossTexture");
  8907. PBRStandardMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  8908. PBRStandardMaterial.PARALLAXTEXTURE = Shader3D.propertyNameToID("u_ParallaxTexture");
  8909. PBRStandardMaterial.OCCLUSIONTEXTURE = Shader3D.propertyNameToID("u_OcclusionTexture");
  8910. PBRStandardMaterial.EMISSIONTEXTURE = Shader3D.propertyNameToID("u_EmissionTexture");
  8911. PBRStandardMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  8912. PBRStandardMaterial.EMISSIONCOLOR = Shader3D.propertyNameToID("u_EmissionColor");
  8913. PBRStandardMaterial.METALLIC = Shader3D.propertyNameToID("u_metallic");
  8914. PBRStandardMaterial.SMOOTHNESS = Shader3D.propertyNameToID("u_smoothness");
  8915. PBRStandardMaterial.SMOOTHNESSSCALE = Shader3D.propertyNameToID("u_smoothnessScale");
  8916. PBRStandardMaterial.SMOOTHNESSSOURCE = -1;
  8917. PBRStandardMaterial.OCCLUSIONSTRENGTH = Shader3D.propertyNameToID("u_occlusionStrength");
  8918. PBRStandardMaterial.NORMALSCALE = Shader3D.propertyNameToID("u_normalScale");
  8919. PBRStandardMaterial.PARALLAXSCALE = Shader3D.propertyNameToID("u_parallaxScale");
  8920. PBRStandardMaterial.ENABLEEMISSION = -1;
  8921. PBRStandardMaterial.ENABLEREFLECT = -1;
  8922. PBRStandardMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  8923. PBRStandardMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  8924. PBRStandardMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  8925. PBRStandardMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  8926. PBRStandardMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  8927. PBRStandardMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  8928. PBRStandardMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  8929. class SkyBoxMaterial extends BaseMaterial {
  8930. constructor() {
  8931. super();
  8932. this.setShaderName("SkyBox");
  8933. this.tintColor = new Vector4(0.5, 0.5, 0.5, 0.5);
  8934. this.exposure = 1.0;
  8935. this.rotation = 0;
  8936. }
  8937. static __initDefine__() {
  8938. }
  8939. get tintColor() {
  8940. return this._shaderValues.getVector(SkyBoxMaterial.TINTCOLOR);
  8941. }
  8942. set tintColor(value) {
  8943. this._shaderValues.setVector(SkyBoxMaterial.TINTCOLOR, value);
  8944. }
  8945. get exposure() {
  8946. return this._shaderValues.getNumber(SkyBoxMaterial.EXPOSURE);
  8947. }
  8948. set exposure(value) {
  8949. this._shaderValues.setNumber(SkyBoxMaterial.EXPOSURE, value);
  8950. }
  8951. get rotation() {
  8952. return this._shaderValues.getNumber(SkyBoxMaterial.ROTATION);
  8953. }
  8954. set rotation(value) {
  8955. this._shaderValues.setNumber(SkyBoxMaterial.ROTATION, value);
  8956. }
  8957. get textureCube() {
  8958. return this._shaderValues.getTexture(SkyBoxMaterial.TEXTURECUBE);
  8959. }
  8960. set textureCube(value) {
  8961. this._shaderValues.setTexture(SkyBoxMaterial.TEXTURECUBE, value);
  8962. }
  8963. clone() {
  8964. var dest = new SkyBoxMaterial();
  8965. this.cloneTo(dest);
  8966. return dest;
  8967. }
  8968. }
  8969. SkyBoxMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_TintColor");
  8970. SkyBoxMaterial.EXPOSURE = Shader3D.propertyNameToID("u_Exposure");
  8971. SkyBoxMaterial.ROTATION = Shader3D.propertyNameToID("u_Rotation");
  8972. SkyBoxMaterial.TEXTURECUBE = Shader3D.propertyNameToID("u_CubeTexture");
  8973. class SkyProceduralMaterial extends BaseMaterial {
  8974. constructor() {
  8975. super();
  8976. this.setShaderName("SkyBoxProcedural");
  8977. this.sunDisk = SkyProceduralMaterial.SUN_HIGH_QUALITY;
  8978. this.sunSize = 0.04;
  8979. this.sunSizeConvergence = 5;
  8980. this.atmosphereThickness = 1.0;
  8981. this.skyTint = new Vector4(0.5, 0.5, 0.5, 1.0);
  8982. this.groundTint = new Vector4(0.369, 0.349, 0.341, 1.0);
  8983. this.exposure = 1.3;
  8984. }
  8985. static __initDefine__() {
  8986. SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY = Shader3D.getDefineByName("SUN_HIGH_QUALITY");
  8987. SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE = Shader3D.getDefineByName("SUN_SIMPLE");
  8988. }
  8989. get sunDisk() {
  8990. return this._sunDisk;
  8991. }
  8992. set sunDisk(value) {
  8993. switch (value) {
  8994. case SkyProceduralMaterial.SUN_HIGH_QUALITY:
  8995. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  8996. this._shaderValues.addDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  8997. break;
  8998. case SkyProceduralMaterial.SUN_SIMPLE:
  8999. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  9000. this._shaderValues.addDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  9001. break;
  9002. case SkyProceduralMaterial.SUN_NODE:
  9003. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  9004. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  9005. break;
  9006. default:
  9007. throw "SkyBoxProceduralMaterial: unknown sun value.";
  9008. }
  9009. this._sunDisk = value;
  9010. }
  9011. get sunSize() {
  9012. return this._shaderValues.getNumber(SkyProceduralMaterial.SUNSIZE);
  9013. }
  9014. set sunSize(value) {
  9015. value = Math.min(Math.max(0.0, value), 1.0);
  9016. this._shaderValues.setNumber(SkyProceduralMaterial.SUNSIZE, value);
  9017. }
  9018. get sunSizeConvergence() {
  9019. return this._shaderValues.getNumber(SkyProceduralMaterial.SUNSIZECONVERGENCE);
  9020. }
  9021. set sunSizeConvergence(value) {
  9022. value = Math.min(Math.max(0.0, value), 20.0);
  9023. this._shaderValues.setNumber(SkyProceduralMaterial.SUNSIZECONVERGENCE, value);
  9024. }
  9025. get atmosphereThickness() {
  9026. return this._shaderValues.getNumber(SkyProceduralMaterial.ATMOSPHERETHICKNESS);
  9027. }
  9028. set atmosphereThickness(value) {
  9029. value = Math.min(Math.max(0.0, value), 5.0);
  9030. this._shaderValues.setNumber(SkyProceduralMaterial.ATMOSPHERETHICKNESS, value);
  9031. }
  9032. get skyTint() {
  9033. return this._shaderValues.getVector(SkyProceduralMaterial.SKYTINT);
  9034. }
  9035. set skyTint(value) {
  9036. this._shaderValues.setVector(SkyProceduralMaterial.SKYTINT, value);
  9037. }
  9038. get groundTint() {
  9039. return this._shaderValues.getVector(SkyProceduralMaterial.GROUNDTINT);
  9040. }
  9041. set groundTint(value) {
  9042. this._shaderValues.setVector(SkyProceduralMaterial.GROUNDTINT, value);
  9043. }
  9044. get exposure() {
  9045. return this._shaderValues.getNumber(SkyProceduralMaterial.EXPOSURE);
  9046. }
  9047. set exposure(value) {
  9048. value = Math.min(Math.max(0.0, value), 8.0);
  9049. this._shaderValues.setNumber(SkyProceduralMaterial.EXPOSURE, value);
  9050. }
  9051. clone() {
  9052. var dest = new SkyProceduralMaterial();
  9053. this.cloneTo(dest);
  9054. return dest;
  9055. }
  9056. }
  9057. SkyProceduralMaterial.SUN_NODE = 0;
  9058. SkyProceduralMaterial.SUN_SIMPLE = 1;
  9059. SkyProceduralMaterial.SUN_HIGH_QUALITY = 2;
  9060. SkyProceduralMaterial.SUNSIZE = Shader3D.propertyNameToID("u_SunSize");
  9061. SkyProceduralMaterial.SUNSIZECONVERGENCE = Shader3D.propertyNameToID("u_SunSizeConvergence");
  9062. SkyProceduralMaterial.ATMOSPHERETHICKNESS = Shader3D.propertyNameToID("u_AtmosphereThickness");
  9063. SkyProceduralMaterial.SKYTINT = Shader3D.propertyNameToID("u_SkyTint");
  9064. SkyProceduralMaterial.GROUNDTINT = Shader3D.propertyNameToID("u_GroundTint");
  9065. SkyProceduralMaterial.EXPOSURE = Shader3D.propertyNameToID("u_Exposure");
  9066. class UnlitMaterial extends BaseMaterial {
  9067. constructor() {
  9068. super();
  9069. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  9070. this._albedoIntensity = 1.0;
  9071. this._enableVertexColor = false;
  9072. this.setShaderName("Unlit");
  9073. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  9074. this.renderMode = UnlitMaterial.RENDERMODE_OPAQUE;
  9075. }
  9076. static __initDefine__() {
  9077. UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE = Shader3D.getDefineByName("ALBEDOTEXTURE");
  9078. UnlitMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  9079. UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR = Shader3D.getDefineByName("ENABLEVERTEXCOLOR");
  9080. }
  9081. get _ColorR() {
  9082. return this._albedoColor.x;
  9083. }
  9084. set _ColorR(value) {
  9085. this._albedoColor.x = value;
  9086. this.albedoColor = this._albedoColor;
  9087. }
  9088. get _ColorG() {
  9089. return this._albedoColor.y;
  9090. }
  9091. set _ColorG(value) {
  9092. this._albedoColor.y = value;
  9093. this.albedoColor = this._albedoColor;
  9094. }
  9095. get _ColorB() {
  9096. return this._albedoColor.z;
  9097. }
  9098. set _ColorB(value) {
  9099. this._albedoColor.z = value;
  9100. this.albedoColor = this._albedoColor;
  9101. }
  9102. get _ColorA() {
  9103. return this._albedoColor.w;
  9104. }
  9105. set _ColorA(value) {
  9106. this._albedoColor.w = value;
  9107. this.albedoColor = this._albedoColor;
  9108. }
  9109. get _AlbedoIntensity() {
  9110. return this._albedoIntensity;
  9111. }
  9112. set _AlbedoIntensity(value) {
  9113. if (this._albedoIntensity !== value) {
  9114. var finalAlbedo = this._shaderValues.getVector(UnlitMaterial.ALBEDOCOLOR);
  9115. Vector4.scale(this._albedoColor, value, finalAlbedo);
  9116. this._albedoIntensity = value;
  9117. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, finalAlbedo);
  9118. }
  9119. }
  9120. get _MainTex_STX() {
  9121. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).x;
  9122. }
  9123. set _MainTex_STX(x) {
  9124. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  9125. tilOff.x = x;
  9126. this.tilingOffset = tilOff;
  9127. }
  9128. get _MainTex_STY() {
  9129. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).y;
  9130. }
  9131. set _MainTex_STY(y) {
  9132. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  9133. tilOff.y = y;
  9134. this.tilingOffset = tilOff;
  9135. }
  9136. get _MainTex_STZ() {
  9137. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).z;
  9138. }
  9139. set _MainTex_STZ(z) {
  9140. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  9141. tilOff.z = z;
  9142. this.tilingOffset = tilOff;
  9143. }
  9144. get _MainTex_STW() {
  9145. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).w;
  9146. }
  9147. set _MainTex_STW(w) {
  9148. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  9149. tilOff.w = w;
  9150. this.tilingOffset = tilOff;
  9151. }
  9152. get _Cutoff() {
  9153. return this.alphaTestValue;
  9154. }
  9155. set _Cutoff(value) {
  9156. this.alphaTestValue = value;
  9157. }
  9158. get albedoColorR() {
  9159. return this._ColorR;
  9160. }
  9161. set albedoColorR(value) {
  9162. this._ColorR = value;
  9163. }
  9164. get albedoColorG() {
  9165. return this._ColorG;
  9166. }
  9167. set albedoColorG(value) {
  9168. this._ColorG = value;
  9169. }
  9170. get albedoColorB() {
  9171. return this._ColorB;
  9172. }
  9173. set albedoColorB(value) {
  9174. this._ColorB = value;
  9175. }
  9176. get albedoColorA() {
  9177. return this._ColorA;
  9178. }
  9179. set albedoColorA(value) {
  9180. this._ColorA = value;
  9181. }
  9182. get albedoColor() {
  9183. return this._albedoColor;
  9184. }
  9185. set albedoColor(value) {
  9186. var finalAlbedo = this._shaderValues.getVector(UnlitMaterial.ALBEDOCOLOR);
  9187. Vector4.scale(value, this._albedoIntensity, finalAlbedo);
  9188. this._albedoColor = value;
  9189. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, finalAlbedo);
  9190. }
  9191. get albedoIntensity() {
  9192. return this._albedoIntensity;
  9193. }
  9194. set albedoIntensity(value) {
  9195. this._AlbedoIntensity = value;
  9196. }
  9197. get albedoTexture() {
  9198. return this._shaderValues.getTexture(UnlitMaterial.ALBEDOTEXTURE);
  9199. }
  9200. set albedoTexture(value) {
  9201. if (value)
  9202. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  9203. else
  9204. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  9205. this._shaderValues.setTexture(UnlitMaterial.ALBEDOTEXTURE, value);
  9206. }
  9207. get tilingOffsetX() {
  9208. return this._MainTex_STX;
  9209. }
  9210. set tilingOffsetX(x) {
  9211. this._MainTex_STX = x;
  9212. }
  9213. get tilingOffsetY() {
  9214. return this._MainTex_STY;
  9215. }
  9216. set tilingOffsetY(y) {
  9217. this._MainTex_STY = y;
  9218. }
  9219. get tilingOffsetZ() {
  9220. return this._MainTex_STZ;
  9221. }
  9222. set tilingOffsetZ(z) {
  9223. this._MainTex_STZ = z;
  9224. }
  9225. get tilingOffsetW() {
  9226. return this._MainTex_STW;
  9227. }
  9228. set tilingOffsetW(w) {
  9229. this._MainTex_STW = w;
  9230. }
  9231. get tilingOffset() {
  9232. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  9233. }
  9234. set tilingOffset(value) {
  9235. if (value) {
  9236. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  9237. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  9238. else
  9239. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  9240. }
  9241. else {
  9242. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  9243. }
  9244. this._shaderValues.setVector(UnlitMaterial.TILINGOFFSET, value);
  9245. }
  9246. get enableVertexColor() {
  9247. return this._enableVertexColor;
  9248. }
  9249. set enableVertexColor(value) {
  9250. this._enableVertexColor = value;
  9251. if (value)
  9252. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  9253. else
  9254. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  9255. }
  9256. set renderMode(value) {
  9257. switch (value) {
  9258. case UnlitMaterial.RENDERMODE_OPAQUE:
  9259. this.alphaTest = false;
  9260. this.renderQueue = BaseMaterial.RENDERQUEUE_OPAQUE;
  9261. this.depthWrite = true;
  9262. this.cull = RenderState.CULL_BACK;
  9263. this.blend = RenderState.BLEND_DISABLE;
  9264. this.depthTest = RenderState.DEPTHTEST_LESS;
  9265. break;
  9266. case UnlitMaterial.RENDERMODE_CUTOUT:
  9267. this.renderQueue = BaseMaterial.RENDERQUEUE_ALPHATEST;
  9268. this.alphaTest = true;
  9269. this.depthWrite = true;
  9270. this.cull = RenderState.CULL_BACK;
  9271. this.blend = RenderState.BLEND_DISABLE;
  9272. this.depthTest = RenderState.DEPTHTEST_LESS;
  9273. break;
  9274. case UnlitMaterial.RENDERMODE_TRANSPARENT:
  9275. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  9276. this.alphaTest = false;
  9277. this.depthWrite = false;
  9278. this.cull = RenderState.CULL_BACK;
  9279. this.blend = RenderState.BLEND_ENABLE_ALL;
  9280. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  9281. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  9282. this.depthTest = RenderState.DEPTHTEST_LESS;
  9283. break;
  9284. default:
  9285. throw new Error("UnlitMaterial : renderMode value error.");
  9286. }
  9287. }
  9288. get depthWrite() {
  9289. return this._shaderValues.getBool(UnlitMaterial.DEPTH_WRITE);
  9290. }
  9291. set depthWrite(value) {
  9292. this._shaderValues.setBool(UnlitMaterial.DEPTH_WRITE, value);
  9293. }
  9294. get cull() {
  9295. return this._shaderValues.getInt(UnlitMaterial.CULL);
  9296. }
  9297. set cull(value) {
  9298. this._shaderValues.setInt(UnlitMaterial.CULL, value);
  9299. }
  9300. get blend() {
  9301. return this._shaderValues.getInt(UnlitMaterial.BLEND);
  9302. }
  9303. set blend(value) {
  9304. this._shaderValues.setInt(UnlitMaterial.BLEND, value);
  9305. }
  9306. get blendSrc() {
  9307. return this._shaderValues.getInt(UnlitMaterial.BLEND_SRC);
  9308. }
  9309. set blendSrc(value) {
  9310. this._shaderValues.setInt(UnlitMaterial.BLEND_SRC, value);
  9311. }
  9312. get blendDst() {
  9313. return this._shaderValues.getInt(UnlitMaterial.BLEND_DST);
  9314. }
  9315. set blendDst(value) {
  9316. this._shaderValues.setInt(UnlitMaterial.BLEND_DST, value);
  9317. }
  9318. get depthTest() {
  9319. return this._shaderValues.getInt(UnlitMaterial.DEPTH_TEST);
  9320. }
  9321. set depthTest(value) {
  9322. this._shaderValues.setInt(UnlitMaterial.DEPTH_TEST, value);
  9323. }
  9324. clone() {
  9325. var dest = new UnlitMaterial();
  9326. this.cloneTo(dest);
  9327. return dest;
  9328. }
  9329. }
  9330. UnlitMaterial.RENDERMODE_OPAQUE = 0;
  9331. UnlitMaterial.RENDERMODE_CUTOUT = 1;
  9332. UnlitMaterial.RENDERMODE_TRANSPARENT = 2;
  9333. UnlitMaterial.RENDERMODE_ADDTIVE = 3;
  9334. UnlitMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  9335. UnlitMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  9336. UnlitMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  9337. UnlitMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  9338. UnlitMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  9339. UnlitMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  9340. UnlitMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  9341. UnlitMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  9342. UnlitMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  9343. class WaterPrimaryMaterial extends BaseMaterial {
  9344. constructor() {
  9345. super();
  9346. this.setShaderName("WaterPrimary");
  9347. this._shaderValues.setVector(WaterPrimaryMaterial.HORIZONCOLOR, new Vector4(0.172, 0.463, 0.435, 0));
  9348. this._shaderValues.setNumber(WaterPrimaryMaterial.WAVESCALE, 0.15);
  9349. this._shaderValues.setVector(WaterPrimaryMaterial.WAVESPEED, new Vector4(19, 9, -16, -7));
  9350. }
  9351. static __initDefine__() {
  9352. WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  9353. WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE = Shader3D.getDefineByName("NORMALTEXTURE");
  9354. }
  9355. get horizonColor() {
  9356. return this._shaderValues.getVector(WaterPrimaryMaterial.HORIZONCOLOR);
  9357. }
  9358. set horizonColor(value) {
  9359. this._shaderValues.setVector(WaterPrimaryMaterial.HORIZONCOLOR, value);
  9360. }
  9361. get mainTexture() {
  9362. return this._shaderValues.getTexture(WaterPrimaryMaterial.MAINTEXTURE);
  9363. }
  9364. set mainTexture(value) {
  9365. if (value)
  9366. this._shaderValues.addDefine(WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE);
  9367. else
  9368. this._shaderValues.removeDefine(WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE);
  9369. this._shaderValues.setTexture(WaterPrimaryMaterial.MAINTEXTURE, value);
  9370. }
  9371. get normalTexture() {
  9372. return this._shaderValues.getTexture(WaterPrimaryMaterial.NORMALTEXTURE);
  9373. }
  9374. set normalTexture(value) {
  9375. if (value)
  9376. this._shaderValues.addDefine(WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE);
  9377. else
  9378. this._shaderValues.removeDefine(WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE);
  9379. this._shaderValues.setTexture(WaterPrimaryMaterial.NORMALTEXTURE, value);
  9380. }
  9381. get waveScale() {
  9382. return this._shaderValues.getNumber(WaterPrimaryMaterial.WAVESCALE);
  9383. }
  9384. set waveScale(value) {
  9385. this._shaderValues.setNumber(WaterPrimaryMaterial.WAVESCALE, value);
  9386. }
  9387. get waveSpeed() {
  9388. return this._shaderValues.getVector(WaterPrimaryMaterial.WAVESPEED);
  9389. }
  9390. set waveSpeed(value) {
  9391. this._shaderValues.setVector(WaterPrimaryMaterial.WAVESPEED, value);
  9392. }
  9393. clone() {
  9394. var dest = new WaterPrimaryMaterial();
  9395. this.cloneTo(dest);
  9396. return dest;
  9397. }
  9398. }
  9399. WaterPrimaryMaterial.HORIZONCOLOR = Shader3D.propertyNameToID("u_HorizonColor");
  9400. WaterPrimaryMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_MainTexture");
  9401. WaterPrimaryMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  9402. WaterPrimaryMaterial.WAVESCALE = Shader3D.propertyNameToID("u_WaveScale");
  9403. WaterPrimaryMaterial.WAVESPEED = Shader3D.propertyNameToID("u_WaveSpeed");
  9404. class Color {
  9405. constructor(r = 1, g = 1, b = 1, a = 1) {
  9406. this.r = r;
  9407. this.g = g;
  9408. this.b = b;
  9409. this.a = a;
  9410. }
  9411. static gammaToLinearSpace(value) {
  9412. if (value <= 0.04045)
  9413. return value / 12.92;
  9414. else if (value < 1.0)
  9415. return Math.pow((value + 0.055) / 1.055, 2.4);
  9416. else
  9417. return Math.pow(value, 2.4);
  9418. }
  9419. static linearToGammaSpace(value) {
  9420. if (value <= 0.0)
  9421. return 0.0;
  9422. else if (value <= 0.0031308)
  9423. return 12.92 * value;
  9424. else if (value <= 1.0)
  9425. return 1.055 * Math.pow(value, 0.41666) - 0.055;
  9426. else
  9427. return Math.pow(value, 0.41666);
  9428. }
  9429. toLinear(out) {
  9430. out.r = Color.gammaToLinearSpace(this.r);
  9431. out.g = Color.gammaToLinearSpace(this.g);
  9432. out.b = Color.gammaToLinearSpace(this.b);
  9433. }
  9434. toGamma(out) {
  9435. out.r = Color.linearToGammaSpace(this.r);
  9436. out.g = Color.linearToGammaSpace(this.g);
  9437. out.b = Color.linearToGammaSpace(this.b);
  9438. }
  9439. cloneTo(destObject) {
  9440. var destColor = destObject;
  9441. destColor.r = this.r;
  9442. destColor.g = this.g;
  9443. destColor.b = this.b;
  9444. destColor.a = this.a;
  9445. }
  9446. clone() {
  9447. var dest = new Color();
  9448. this.cloneTo(dest);
  9449. return dest;
  9450. }
  9451. forNativeElement() {
  9452. }
  9453. }
  9454. Color.RED = new Color(1, 0, 0, 1);
  9455. Color.GREEN = new Color(0, 1, 0, 1);
  9456. Color.BLUE = new Color(0, 0, 1, 1);
  9457. Color.CYAN = new Color(0, 1, 1, 1);
  9458. Color.YELLOW = new Color(1, 0.92, 0.016, 1);
  9459. Color.MAGENTA = new Color(1, 0, 1, 1);
  9460. Color.GRAY = new Color(0.5, 0.5, 0.5, 1);
  9461. Color.WHITE = new Color(1, 1, 1, 1);
  9462. Color.BLACK = new Color(0, 0, 0, 1);
  9463. class DynamicBatchManager {
  9464. constructor() {
  9465. this._batchRenderElementPool = [];
  9466. }
  9467. static _registerManager(manager) {
  9468. DynamicBatchManager._managers.push(manager);
  9469. }
  9470. _clear() {
  9471. this._batchRenderElementPoolIndex = 0;
  9472. }
  9473. _getBatchRenderElementFromPool() {
  9474. throw "StaticBatch:must override this function.";
  9475. }
  9476. dispose() {
  9477. }
  9478. }
  9479. DynamicBatchManager._managers = [];
  9480. class Transform3D extends Laya.EventDispatcher {
  9481. constructor(owner) {
  9482. super();
  9483. this._localPosition = new Vector3(0, 0, 0);
  9484. this._localRotation = new Quaternion(0, 0, 0, 1);
  9485. this._localScale = new Vector3(1, 1, 1);
  9486. this._localRotationEuler = new Vector3(0, 0, 0);
  9487. this._localMatrix = new Matrix4x4();
  9488. this._position = new Vector3(0, 0, 0);
  9489. this._rotation = new Quaternion(0, 0, 0, 1);
  9490. this._scale = new Vector3(1, 1, 1);
  9491. this._rotationEuler = new Vector3(0, 0, 0);
  9492. this._worldMatrix = new Matrix4x4();
  9493. this._children = null;
  9494. this._parent = null;
  9495. this._dummy = null;
  9496. this._transformFlag = 0;
  9497. this._owner = owner;
  9498. this._children = [];
  9499. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION | Transform3D.TRANSFORM_LOCALEULER | Transform3D.TRANSFORM_LOCALMATRIX, false);
  9500. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER | Transform3D.TRANSFORM_WORLDSCALE | Transform3D.TRANSFORM_WORLDMATRIX, true);
  9501. }
  9502. get _isFrontFaceInvert() {
  9503. var scale = this.getWorldLossyScale();
  9504. var isInvert = scale.x < 0;
  9505. (scale.y < 0) && (isInvert = !isInvert);
  9506. (scale.z < 0) && (isInvert = !isInvert);
  9507. return isInvert;
  9508. }
  9509. get owner() {
  9510. return this._owner;
  9511. }
  9512. get worldNeedUpdate() {
  9513. return this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX);
  9514. }
  9515. get localPositionX() {
  9516. return this._localPosition.x;
  9517. }
  9518. set localPositionX(x) {
  9519. this._localPosition.x = x;
  9520. this.localPosition = this._localPosition;
  9521. }
  9522. get localPositionY() {
  9523. return this._localPosition.y;
  9524. }
  9525. set localPositionY(y) {
  9526. this._localPosition.y = y;
  9527. this.localPosition = this._localPosition;
  9528. }
  9529. get localPositionZ() {
  9530. return this._localPosition.z;
  9531. }
  9532. set localPositionZ(z) {
  9533. this._localPosition.z = z;
  9534. this.localPosition = this._localPosition;
  9535. }
  9536. get localPosition() {
  9537. return this._localPosition;
  9538. }
  9539. set localPosition(value) {
  9540. if (this._localPosition !== value)
  9541. value.cloneTo(this._localPosition);
  9542. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, true);
  9543. this._onWorldPositionTransform();
  9544. }
  9545. get localRotationX() {
  9546. return this.localRotation.x;
  9547. }
  9548. set localRotationX(x) {
  9549. this._localRotation.x = x;
  9550. this.localRotation = this._localRotation;
  9551. }
  9552. get localRotationY() {
  9553. return this.localRotation.y;
  9554. }
  9555. set localRotationY(y) {
  9556. this._localRotation.y = y;
  9557. this.localRotation = this._localRotation;
  9558. }
  9559. get localRotationZ() {
  9560. return this.localRotation.z;
  9561. }
  9562. set localRotationZ(z) {
  9563. this._localRotation.z = z;
  9564. this.localRotation = this._localRotation;
  9565. }
  9566. get localRotationW() {
  9567. return this.localRotation.w;
  9568. }
  9569. set localRotationW(w) {
  9570. this._localRotation.w = w;
  9571. this.localRotation = this._localRotation;
  9572. }
  9573. get localRotation() {
  9574. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION)) {
  9575. var eulerE = this._localRotationEuler;
  9576. Quaternion.createFromYawPitchRoll(eulerE.y / Transform3D._angleToRandin, eulerE.x / Transform3D._angleToRandin, eulerE.z / Transform3D._angleToRandin, this._localRotation);
  9577. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION, false);
  9578. }
  9579. return this._localRotation;
  9580. }
  9581. set localRotation(value) {
  9582. if (this._localRotation !== value)
  9583. value.cloneTo(this._localRotation);
  9584. this._localRotation.normalize(this._localRotation);
  9585. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER | Transform3D.TRANSFORM_LOCALMATRIX, true);
  9586. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION, false);
  9587. this._onWorldRotationTransform();
  9588. }
  9589. get localScaleX() {
  9590. return this._localScale.x;
  9591. }
  9592. set localScaleX(value) {
  9593. this._localScale.x = value;
  9594. this.localScale = this._localScale;
  9595. }
  9596. get localScaleY() {
  9597. return this._localScale.y;
  9598. }
  9599. set localScaleY(value) {
  9600. this._localScale.y = value;
  9601. this.localScale = this._localScale;
  9602. }
  9603. get localScaleZ() {
  9604. return this._localScale.z;
  9605. }
  9606. set localScaleZ(value) {
  9607. this._localScale.z = value;
  9608. this.localScale = this._localScale;
  9609. }
  9610. get localScale() {
  9611. return this._localScale;
  9612. }
  9613. set localScale(value) {
  9614. if (this._localScale !== value)
  9615. value.cloneTo(this._localScale);
  9616. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, true);
  9617. this._onWorldScaleTransform();
  9618. }
  9619. get localRotationEulerX() {
  9620. return this.localRotationEuler.x;
  9621. }
  9622. set localRotationEulerX(value) {
  9623. this._localRotationEuler.x = value;
  9624. this.localRotationEuler = this._localRotationEuler;
  9625. }
  9626. get localRotationEulerY() {
  9627. return this.localRotationEuler.y;
  9628. }
  9629. set localRotationEulerY(value) {
  9630. this._localRotationEuler.y = value;
  9631. this.localRotationEuler = this._localRotationEuler;
  9632. }
  9633. get localRotationEulerZ() {
  9634. return this.localRotationEuler.z;
  9635. }
  9636. set localRotationEulerZ(value) {
  9637. this._localRotationEuler.z = value;
  9638. this.localRotationEuler = this._localRotationEuler;
  9639. }
  9640. get localRotationEuler() {
  9641. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALEULER)) {
  9642. this._localRotation.getYawPitchRoll(Transform3D._tempVector30);
  9643. var euler = Transform3D._tempVector30;
  9644. var localRotationEuler = this._localRotationEuler;
  9645. localRotationEuler.x = euler.y * Transform3D._angleToRandin;
  9646. localRotationEuler.y = euler.x * Transform3D._angleToRandin;
  9647. localRotationEuler.z = euler.z * Transform3D._angleToRandin;
  9648. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, false);
  9649. }
  9650. return this._localRotationEuler;
  9651. }
  9652. set localRotationEuler(value) {
  9653. if (this._localRotationEuler !== value)
  9654. value.cloneTo(this._localRotationEuler);
  9655. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, false);
  9656. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION | Transform3D.TRANSFORM_LOCALMATRIX, true);
  9657. this._onWorldRotationTransform();
  9658. }
  9659. get localMatrix() {
  9660. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX)) {
  9661. Matrix4x4.createAffineTransformation(this._localPosition, this.localRotation, this._localScale, this._localMatrix);
  9662. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, false);
  9663. }
  9664. return this._localMatrix;
  9665. }
  9666. set localMatrix(value) {
  9667. if (this._localMatrix !== value)
  9668. value.cloneTo(this._localMatrix);
  9669. this._localMatrix.decomposeTransRotScale(this._localPosition, this._localRotation, this._localScale);
  9670. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, true);
  9671. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, false);
  9672. this._onWorldTransform();
  9673. }
  9674. get position() {
  9675. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  9676. if (this._parent != null) {
  9677. var worldMatE = this.worldMatrix.elements;
  9678. this._position.x = worldMatE[12];
  9679. this._position.y = worldMatE[13];
  9680. this._position.z = worldMatE[14];
  9681. }
  9682. else {
  9683. this._localPosition.cloneTo(this._position);
  9684. }
  9685. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  9686. }
  9687. return this._position;
  9688. }
  9689. set position(value) {
  9690. if (this._parent != null) {
  9691. var parentInvMat = Transform3D._tempMatrix0;
  9692. this._parent.worldMatrix.invert(parentInvMat);
  9693. Vector3.transformCoordinate(value, parentInvMat, this._localPosition);
  9694. }
  9695. else {
  9696. value.cloneTo(this._localPosition);
  9697. }
  9698. this.localPosition = this._localPosition;
  9699. if (this._position !== value)
  9700. value.cloneTo(this._position);
  9701. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  9702. }
  9703. get rotation() {
  9704. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION)) {
  9705. if (this._parent != null)
  9706. Quaternion.multiply(this._parent.rotation, this.localRotation, this._rotation);
  9707. else
  9708. this.localRotation.cloneTo(this._rotation);
  9709. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  9710. }
  9711. return this._rotation;
  9712. }
  9713. set rotation(value) {
  9714. if (this._parent != null) {
  9715. this._parent.rotation.invert(Transform3D._tempQuaternion0);
  9716. Quaternion.multiply(Transform3D._tempQuaternion0, value, this._localRotation);
  9717. }
  9718. else {
  9719. value.cloneTo(this._localRotation);
  9720. }
  9721. this.localRotation = this._localRotation;
  9722. if (value !== this._rotation)
  9723. value.cloneTo(this._rotation);
  9724. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  9725. }
  9726. get rotationEuler() {
  9727. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  9728. this.rotation.getYawPitchRoll(Transform3D._tempVector30);
  9729. var eulerE = Transform3D._tempVector30;
  9730. var rotationEulerE = this._rotationEuler;
  9731. rotationEulerE.x = eulerE.y * Transform3D._angleToRandin;
  9732. rotationEulerE.y = eulerE.x * Transform3D._angleToRandin;
  9733. rotationEulerE.z = eulerE.z * Transform3D._angleToRandin;
  9734. this._setTransformFlag(Transform3D.TRANSFORM_WORLDEULER, false);
  9735. }
  9736. return this._rotationEuler;
  9737. }
  9738. set rotationEuler(value) {
  9739. Quaternion.createFromYawPitchRoll(value.y / Transform3D._angleToRandin, value.x / Transform3D._angleToRandin, value.z / Transform3D._angleToRandin, this._rotation);
  9740. this.rotation = this._rotation;
  9741. if (this._rotationEuler !== value)
  9742. value.cloneTo(this._rotationEuler);
  9743. this._setTransformFlag(Transform3D.TRANSFORM_WORLDEULER, false);
  9744. }
  9745. get worldMatrix() {
  9746. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX)) {
  9747. if (this._parent != null)
  9748. Matrix4x4.multiply(this._parent.worldMatrix, this.localMatrix, this._worldMatrix);
  9749. else
  9750. this.localMatrix.cloneTo(this._worldMatrix);
  9751. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX, false);
  9752. }
  9753. return this._worldMatrix;
  9754. }
  9755. set worldMatrix(value) {
  9756. if (this._parent === null) {
  9757. value.cloneTo(this._localMatrix);
  9758. }
  9759. else {
  9760. this._parent.worldMatrix.invert(this._localMatrix);
  9761. Matrix4x4.multiply(this._localMatrix, value, this._localMatrix);
  9762. }
  9763. this.localMatrix = this._localMatrix;
  9764. if (this._worldMatrix !== value)
  9765. value.cloneTo(this._worldMatrix);
  9766. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX, false);
  9767. }
  9768. _getScaleMatrix() {
  9769. var invRotation = Transform3D._tempQuaternion0;
  9770. var invRotationMat = Transform3D._tempMatrix3x30;
  9771. var worldRotScaMat = Transform3D._tempMatrix3x31;
  9772. var scaMat = Transform3D._tempMatrix3x32;
  9773. Matrix3x3.createFromMatrix4x4(this.worldMatrix, worldRotScaMat);
  9774. this.rotation.invert(invRotation);
  9775. Matrix3x3.createRotationQuaternion(invRotation, invRotationMat);
  9776. Matrix3x3.multiply(invRotationMat, worldRotScaMat, scaMat);
  9777. return scaMat;
  9778. }
  9779. _setTransformFlag(type, value) {
  9780. if (value)
  9781. this._transformFlag |= type;
  9782. else
  9783. this._transformFlag &= ~type;
  9784. }
  9785. _getTransformFlag(type) {
  9786. return (this._transformFlag & type) != 0;
  9787. }
  9788. _setParent(value) {
  9789. if (this._parent !== value) {
  9790. if (this._parent) {
  9791. var parentChilds = this._parent._children;
  9792. var index = parentChilds.indexOf(this);
  9793. parentChilds.splice(index, 1);
  9794. }
  9795. if (value) {
  9796. value._children.push(this);
  9797. (value) && (this._onWorldTransform());
  9798. }
  9799. this._parent = value;
  9800. }
  9801. }
  9802. _onWorldPositionRotationTransform() {
  9803. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  9804. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER, true);
  9805. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9806. for (var i = 0, n = this._children.length; i < n; i++)
  9807. this._children[i]._onWorldPositionRotationTransform();
  9808. }
  9809. }
  9810. _onWorldPositionScaleTransform() {
  9811. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  9812. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDSCALE, true);
  9813. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9814. for (var i = 0, n = this._children.length; i < n; i++)
  9815. this._children[i]._onWorldPositionScaleTransform();
  9816. }
  9817. }
  9818. _onWorldPositionTransform() {
  9819. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  9820. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION, true);
  9821. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9822. for (var i = 0, n = this._children.length; i < n; i++)
  9823. this._children[i]._onWorldPositionTransform();
  9824. }
  9825. }
  9826. _onWorldRotationTransform() {
  9827. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  9828. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER, true);
  9829. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9830. for (var i = 0, n = this._children.length; i < n; i++)
  9831. this._children[i]._onWorldPositionRotationTransform();
  9832. }
  9833. }
  9834. _onWorldScaleTransform() {
  9835. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  9836. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDSCALE, true);
  9837. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9838. for (var i = 0, n = this._children.length; i < n; i++)
  9839. this._children[i]._onWorldPositionScaleTransform();
  9840. }
  9841. }
  9842. _onWorldTransform() {
  9843. 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)) {
  9844. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER | Transform3D.TRANSFORM_WORLDSCALE, true);
  9845. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9846. for (var i = 0, n = this._children.length; i < n; i++)
  9847. this._children[i]._onWorldTransform();
  9848. }
  9849. }
  9850. translate(translation, isLocal = true) {
  9851. if (isLocal) {
  9852. Matrix4x4.createFromQuaternion(this.localRotation, Transform3D._tempMatrix0);
  9853. Vector3.transformCoordinate(translation, Transform3D._tempMatrix0, Transform3D._tempVector30);
  9854. Vector3.add(this.localPosition, Transform3D._tempVector30, this._localPosition);
  9855. this.localPosition = this._localPosition;
  9856. }
  9857. else {
  9858. Vector3.add(this.position, translation, this._position);
  9859. this.position = this._position;
  9860. }
  9861. }
  9862. rotate(rotation, isLocal = true, isRadian = true) {
  9863. var rot;
  9864. if (isRadian) {
  9865. rot = rotation;
  9866. }
  9867. else {
  9868. Vector3.scale(rotation, Math.PI / 180.0, Transform3D._tempVector30);
  9869. rot = Transform3D._tempVector30;
  9870. }
  9871. Quaternion.createFromYawPitchRoll(rot.y, rot.x, rot.z, Transform3D._tempQuaternion0);
  9872. if (isLocal) {
  9873. Quaternion.multiply(this._localRotation, Transform3D._tempQuaternion0, this._localRotation);
  9874. this.localRotation = this._localRotation;
  9875. }
  9876. else {
  9877. Quaternion.multiply(Transform3D._tempQuaternion0, this.rotation, this._rotation);
  9878. this.rotation = this._rotation;
  9879. }
  9880. }
  9881. getForward(forward) {
  9882. var worldMatElem = this.worldMatrix.elements;
  9883. forward.x = -worldMatElem[8];
  9884. forward.y = -worldMatElem[9];
  9885. forward.z = -worldMatElem[10];
  9886. }
  9887. getUp(up) {
  9888. var worldMatElem = this.worldMatrix.elements;
  9889. up.x = worldMatElem[4];
  9890. up.y = worldMatElem[5];
  9891. up.z = worldMatElem[6];
  9892. }
  9893. getRight(right) {
  9894. var worldMatElem = this.worldMatrix.elements;
  9895. right.x = worldMatElem[0];
  9896. right.y = worldMatElem[1];
  9897. right.z = worldMatElem[2];
  9898. }
  9899. lookAt(target, up, isLocal = false) {
  9900. var eye;
  9901. if (isLocal) {
  9902. eye = this._localPosition;
  9903. 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)
  9904. return;
  9905. Quaternion.lookAt(this._localPosition, target, up, this._localRotation);
  9906. this._localRotation.invert(this._localRotation);
  9907. this.localRotation = this._localRotation;
  9908. }
  9909. else {
  9910. var worldPosition = this.position;
  9911. eye = worldPosition;
  9912. 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)
  9913. return;
  9914. Quaternion.lookAt(worldPosition, target, up, this._rotation);
  9915. this._rotation.invert(this._rotation);
  9916. this.rotation = this._rotation;
  9917. }
  9918. }
  9919. getWorldLossyScale() {
  9920. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  9921. if (this._parent !== null) {
  9922. var scaMatE = this._getScaleMatrix().elements;
  9923. this._scale.x = scaMatE[0];
  9924. this._scale.y = scaMatE[4];
  9925. this._scale.z = scaMatE[8];
  9926. }
  9927. else {
  9928. this._localScale.cloneTo(this._scale);
  9929. }
  9930. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  9931. }
  9932. return this._scale;
  9933. }
  9934. setWorldLossyScale(value) {
  9935. if (this._parent !== null) {
  9936. var scaleMat = Transform3D._tempMatrix3x33;
  9937. var localScaleMat = Transform3D._tempMatrix3x33;
  9938. var localScaleMatE = localScaleMat.elements;
  9939. var parInvScaleMat = this._parent._getScaleMatrix();
  9940. parInvScaleMat.invert(parInvScaleMat);
  9941. Matrix3x3.createFromScaling(value, scaleMat);
  9942. Matrix3x3.multiply(parInvScaleMat, scaleMat, localScaleMat);
  9943. this._localScale.x = localScaleMatE[0];
  9944. this._localScale.y = localScaleMatE[4];
  9945. this._localScale.z = localScaleMatE[8];
  9946. }
  9947. else {
  9948. value.cloneTo(this._localScale);
  9949. }
  9950. this.localScale = this._localScale;
  9951. if (this._scale !== value)
  9952. value.cloneTo(this._scale);
  9953. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  9954. }
  9955. get scale() {
  9956. // console.warn("Transfrm3D: discard function,please use getWorldLossyScale instead.");
  9957. return this.getWorldLossyScale();
  9958. }
  9959. set scale(value) {
  9960. // console.warn("Transfrm3D: discard function,please use setWorldLossyScale instead.");
  9961. this.setWorldLossyScale(value);
  9962. }
  9963. }
  9964. Transform3D._tempVector30 = new Vector3();
  9965. Transform3D._tempQuaternion0 = new Quaternion();
  9966. Transform3D._tempMatrix0 = new Matrix4x4();
  9967. Transform3D._tempMatrix3x30 = new Matrix3x3();
  9968. Transform3D._tempMatrix3x31 = new Matrix3x3();
  9969. Transform3D._tempMatrix3x32 = new Matrix3x3();
  9970. Transform3D._tempMatrix3x33 = new Matrix3x3();
  9971. Transform3D.TRANSFORM_LOCALQUATERNION = 0x01;
  9972. Transform3D.TRANSFORM_LOCALEULER = 0x02;
  9973. Transform3D.TRANSFORM_LOCALMATRIX = 0x04;
  9974. Transform3D.TRANSFORM_WORLDPOSITION = 0x08;
  9975. Transform3D.TRANSFORM_WORLDQUATERNION = 0x10;
  9976. Transform3D.TRANSFORM_WORLDSCALE = 0x20;
  9977. Transform3D.TRANSFORM_WORLDMATRIX = 0x40;
  9978. Transform3D.TRANSFORM_WORLDEULER = 0x80;
  9979. Transform3D._angleToRandin = 180 / Math.PI;
  9980. class Sprite3D extends Laya.Node {
  9981. constructor(name = null, isStatic = false) {
  9982. super();
  9983. this._needProcessCollisions = false;
  9984. this._needProcessTriggers = false;
  9985. this._id = ++Sprite3D._uniqueIDCounter;
  9986. this._transform = new Transform3D(this);
  9987. this._isStatic = isStatic;
  9988. this.layer = 0;
  9989. this.name = name ? name : "New Sprite3D";
  9990. }
  9991. static __init__() {
  9992. }
  9993. static instantiate(original, parent = null, worldPositionStays = true, position = null, rotation = null) {
  9994. var destSprite3D = original.clone();
  9995. (parent) && (parent.addChild(destSprite3D));
  9996. var transform = destSprite3D.transform;
  9997. if (worldPositionStays) {
  9998. var worldMatrix = transform.worldMatrix;
  9999. original.transform.worldMatrix.cloneTo(worldMatrix);
  10000. transform.worldMatrix = worldMatrix;
  10001. }
  10002. else {
  10003. (position) && (transform.position = position);
  10004. (rotation) && (transform.rotation = rotation);
  10005. }
  10006. return destSprite3D;
  10007. }
  10008. static load(url, complete) {
  10009. Laya.Laya.loader.create(url, complete, null, Sprite3D.HIERARCHY);
  10010. }
  10011. get id() {
  10012. return this._id;
  10013. }
  10014. get layer() {
  10015. return this._layer;
  10016. }
  10017. set layer(value) {
  10018. if (this._layer !== value) {
  10019. if (value >= 0 && value <= 30) {
  10020. this._layer = value;
  10021. }
  10022. else {
  10023. throw new Error("Layer value must be 0-30.");
  10024. }
  10025. }
  10026. }
  10027. get url() {
  10028. return this._url;
  10029. }
  10030. get isStatic() {
  10031. return this._isStatic;
  10032. }
  10033. get transform() {
  10034. return this._transform;
  10035. }
  10036. _setCreateURL(url) {
  10037. this._url = Laya.URL.formatURL(url);
  10038. }
  10039. _changeAnimatorsToLinkSprite3D(sprite3D, isLink, path) {
  10040. var animator = this.getComponent(Animator);
  10041. if (animator) {
  10042. if (!animator.avatar)
  10043. sprite3D._changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path);
  10044. }
  10045. if (this._parent && this._parent instanceof Sprite3D) {
  10046. path.unshift(this._parent.name);
  10047. var p = this._parent;
  10048. (p._hierarchyAnimator) && (p._changeAnimatorsToLinkSprite3D(sprite3D, isLink, path));
  10049. }
  10050. }
  10051. _setHierarchyAnimator(animator, parentAnimator) {
  10052. this._changeHierarchyAnimator(animator);
  10053. this._changeAnimatorAvatar(animator.avatar);
  10054. for (var i = 0, n = this._children.length; i < n; i++) {
  10055. var child = this._children[i];
  10056. (child._hierarchyAnimator == parentAnimator) && (child._setHierarchyAnimator(animator, parentAnimator));
  10057. }
  10058. }
  10059. _clearHierarchyAnimator(animator, parentAnimator) {
  10060. this._changeHierarchyAnimator(parentAnimator);
  10061. this._changeAnimatorAvatar(parentAnimator ? parentAnimator.avatar : null);
  10062. for (var i = 0, n = this._children.length; i < n; i++) {
  10063. var child = this._children[i];
  10064. (child._hierarchyAnimator == animator) && (child._clearHierarchyAnimator(animator, parentAnimator));
  10065. }
  10066. }
  10067. _changeHierarchyAnimatorAvatar(animator, avatar) {
  10068. this._changeAnimatorAvatar(avatar);
  10069. for (var i = 0, n = this._children.length; i < n; i++) {
  10070. var child = this._children[i];
  10071. (child._hierarchyAnimator == animator) && (child._changeHierarchyAnimatorAvatar(animator, avatar));
  10072. }
  10073. }
  10074. _changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path) {
  10075. animator._handleSpriteOwnersBySprite(isLink, path, this);
  10076. for (var i = 0, n = this._children.length; i < n; i++) {
  10077. var child = this._children[i];
  10078. var index = path.length;
  10079. path.push(child.name);
  10080. child._changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path);
  10081. path.splice(index, 1);
  10082. }
  10083. }
  10084. _changeHierarchyAnimator(animator) {
  10085. this._hierarchyAnimator = animator;
  10086. }
  10087. _changeAnimatorAvatar(avatar) {
  10088. }
  10089. _onAdded() {
  10090. if (this._parent instanceof Sprite3D) {
  10091. var parent3D = this._parent;
  10092. this.transform._setParent(parent3D.transform);
  10093. if (parent3D._hierarchyAnimator) {
  10094. (!this._hierarchyAnimator) && (this._setHierarchyAnimator(parent3D._hierarchyAnimator, null));
  10095. parent3D._changeAnimatorsToLinkSprite3D(this, true, [this.name]);
  10096. }
  10097. }
  10098. super._onAdded();
  10099. }
  10100. _onRemoved() {
  10101. super._onRemoved();
  10102. if (this._parent instanceof Sprite3D) {
  10103. var parent3D = this._parent;
  10104. this.transform._setParent(null);
  10105. if (parent3D._hierarchyAnimator) {
  10106. (this._hierarchyAnimator == parent3D._hierarchyAnimator) && (this._clearHierarchyAnimator(parent3D._hierarchyAnimator, null));
  10107. parent3D._changeAnimatorsToLinkSprite3D(this, false, [this.name]);
  10108. }
  10109. }
  10110. }
  10111. _parse(data, spriteMap) {
  10112. (data.isStatic !== undefined) && (this._isStatic = data.isStatic);
  10113. (data.active !== undefined) && (this.active = data.active);
  10114. (data.name != undefined) && (this.name = data.name);
  10115. if (data.position !== undefined) {
  10116. var loccalPosition = this.transform.localPosition;
  10117. loccalPosition.fromArray(data.position);
  10118. this.transform.localPosition = loccalPosition;
  10119. }
  10120. if (data.rotationEuler !== undefined) {
  10121. var localRotationEuler = this.transform.localRotationEuler;
  10122. localRotationEuler.fromArray(data.rotationEuler);
  10123. this.transform.localRotationEuler = localRotationEuler;
  10124. }
  10125. if (data.rotation !== undefined) {
  10126. var localRotation = this.transform.localRotation;
  10127. localRotation.fromArray(data.rotation);
  10128. this.transform.localRotation = localRotation;
  10129. }
  10130. if (data.scale !== undefined) {
  10131. var localScale = this.transform.localScale;
  10132. localScale.fromArray(data.scale);
  10133. this.transform.localScale = localScale;
  10134. }
  10135. (data.layer != undefined) && (this.layer = data.layer);
  10136. }
  10137. _cloneTo(destObject, srcRoot, dstRoot) {
  10138. if (this.destroyed)
  10139. throw new Error("Sprite3D: Can't be cloned if the Sprite3D has destroyed.");
  10140. var destSprite3D = destObject;
  10141. destSprite3D.name = this.name;
  10142. destSprite3D.destroyed = this.destroyed;
  10143. destSprite3D.active = this.active;
  10144. var destLocalPosition = destSprite3D.transform.localPosition;
  10145. this.transform.localPosition.cloneTo(destLocalPosition);
  10146. destSprite3D.transform.localPosition = destLocalPosition;
  10147. var destLocalRotation = destSprite3D.transform.localRotation;
  10148. this.transform.localRotation.cloneTo(destLocalRotation);
  10149. destSprite3D.transform.localRotation = destLocalRotation;
  10150. var destLocalScale = destSprite3D.transform.localScale;
  10151. this.transform.localScale.cloneTo(destLocalScale);
  10152. destSprite3D.transform.localScale = destLocalScale;
  10153. destSprite3D._isStatic = this._isStatic;
  10154. destSprite3D.layer = this.layer;
  10155. super._cloneTo(destSprite3D, srcRoot, dstRoot);
  10156. }
  10157. static _createSprite3DInstance(scrSprite) {
  10158. var node = scrSprite._create();
  10159. var children = scrSprite._children;
  10160. for (var i = 0, n = children.length; i < n; i++) {
  10161. var child = Sprite3D._createSprite3DInstance(children[i]);
  10162. node.addChild(child);
  10163. }
  10164. return node;
  10165. }
  10166. static _parseSprite3DInstance(srcRoot, dstRoot, scrSprite, dstSprite) {
  10167. var srcChildren = scrSprite._children;
  10168. var dstChildren = dstSprite._children;
  10169. for (var i = 0, n = srcChildren.length; i < n; i++)
  10170. Sprite3D._parseSprite3DInstance(srcRoot, dstRoot, srcChildren[i], dstChildren[i]);
  10171. scrSprite._cloneTo(dstSprite, srcRoot, dstRoot);
  10172. }
  10173. clone() {
  10174. var dstSprite3D = Sprite3D._createSprite3DInstance(this);
  10175. Sprite3D._parseSprite3DInstance(this, dstSprite3D, this, dstSprite3D);
  10176. return dstSprite3D;
  10177. }
  10178. destroy(destroyChild = true) {
  10179. if (this.destroyed)
  10180. return;
  10181. super.destroy(destroyChild);
  10182. this._transform = null;
  10183. this._scripts = null;
  10184. this._url && Laya.Loader.clearRes(this._url);
  10185. }
  10186. _create() {
  10187. return new Sprite3D();
  10188. }
  10189. }
  10190. Sprite3D.HIERARCHY = "HIERARCHY";
  10191. Sprite3D.WORLDMATRIX = Shader3D.propertyNameToID("u_WorldMat");
  10192. Sprite3D.MVPMATRIX = Shader3D.propertyNameToID("u_MvpMatrix");
  10193. Sprite3D._uniqueIDCounter = 0;
  10194. class RenderableSprite3D extends Sprite3D {
  10195. constructor(name) {
  10196. super(name);
  10197. }
  10198. static __init__() {
  10199. RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW = Shader3D.getDefineByName("RECEIVESHADOW");
  10200. RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV = Shader3D.getDefineByName("SCALEOFFSETLIGHTINGMAPUV");
  10201. RenderableSprite3D.SAHDERDEFINE_LIGHTMAP = Shader3D.getDefineByName("LIGHTMAP");
  10202. }
  10203. _onInActive() {
  10204. super._onInActive();
  10205. var scene3D = this._scene;
  10206. scene3D._removeRenderObject(this._render);
  10207. (this._render.castShadow) && (scene3D._removeShadowCastRenderObject(this._render));
  10208. }
  10209. _onActive() {
  10210. super._onActive();
  10211. var scene3D = this._scene;
  10212. scene3D._addRenderObject(this._render);
  10213. (this._render.castShadow) && (scene3D._addShadowCastRenderObject(this._render));
  10214. }
  10215. _onActiveInScene() {
  10216. super._onActiveInScene();
  10217. if (ILaya3D.Laya3D._editerEnvironment) {
  10218. var scene = this._scene;
  10219. var pickColor = new Vector4();
  10220. scene._allotPickColorByID(this.id, pickColor);
  10221. scene._pickIdToSprite[this.id] = this;
  10222. this._render._shaderValues.setVector(RenderableSprite3D.PICKCOLOR, pickColor);
  10223. }
  10224. }
  10225. _addToInitStaticBatchManager() {
  10226. }
  10227. _setBelongScene(scene) {
  10228. super._setBelongScene(scene);
  10229. this._render._setBelongScene(scene);
  10230. }
  10231. _setUnBelongScene() {
  10232. this._render._shaderValues.removeDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  10233. super._setUnBelongScene();
  10234. }
  10235. _changeHierarchyAnimator(animator) {
  10236. if (this._hierarchyAnimator) {
  10237. var renderableSprites = this._hierarchyAnimator._renderableSprites;
  10238. renderableSprites.splice(renderableSprites.indexOf(this), 1);
  10239. }
  10240. if (animator)
  10241. animator._renderableSprites.push(this);
  10242. super._changeHierarchyAnimator(animator);
  10243. }
  10244. destroy(destroyChild = true) {
  10245. super.destroy(destroyChild);
  10246. this._render._destroy();
  10247. this._render = null;
  10248. }
  10249. _create() {
  10250. return new RenderableSprite3D(this.name);
  10251. }
  10252. }
  10253. RenderableSprite3D.LIGHTMAPSCALEOFFSET = Shader3D.propertyNameToID("u_LightmapScaleOffset");
  10254. RenderableSprite3D.LIGHTMAP = Shader3D.propertyNameToID("u_LightMap");
  10255. RenderableSprite3D.PICKCOLOR = Shader3D.propertyNameToID("u_PickColor");
  10256. class StaticBatchManager {
  10257. constructor() {
  10258. this._initBatchSprites = [];
  10259. this._staticBatches = {};
  10260. this._batchRenderElementPoolIndex = 0;
  10261. this._batchRenderElementPool = [];
  10262. }
  10263. static _addToStaticBatchQueue(sprite3D, renderableSprite3D) {
  10264. if (sprite3D instanceof RenderableSprite3D)
  10265. renderableSprite3D.push(sprite3D);
  10266. for (var i = 0, n = sprite3D.numChildren; i < n; i++)
  10267. StaticBatchManager._addToStaticBatchQueue(sprite3D._children[i], renderableSprite3D);
  10268. }
  10269. static _registerManager(manager) {
  10270. StaticBatchManager._managers.push(manager);
  10271. }
  10272. static combine(staticBatchRoot, renderableSprite3Ds = null) {
  10273. if (!renderableSprite3Ds) {
  10274. renderableSprite3Ds = [];
  10275. if (staticBatchRoot)
  10276. StaticBatchManager._addToStaticBatchQueue(staticBatchRoot, renderableSprite3Ds);
  10277. }
  10278. var batchSpritesCount = renderableSprite3Ds.length;
  10279. if (batchSpritesCount > 0) {
  10280. for (var i = 0; i < batchSpritesCount; i++) {
  10281. var sprite = renderableSprite3Ds[i];
  10282. if (!sprite.destroyed) {
  10283. if (sprite._render._isPartOfStaticBatch)
  10284. console.warn("StaticBatchManager: Sprite " + sprite.name + " has a part of Static Batch,it will be ignore.");
  10285. else
  10286. sprite._addToInitStaticBatchManager();
  10287. }
  10288. }
  10289. for (var k = 0, m = StaticBatchManager._managers.length; k < m; k++) {
  10290. var manager = StaticBatchManager._managers[k];
  10291. manager._initStaticBatchs(staticBatchRoot);
  10292. }
  10293. }
  10294. }
  10295. _partition(items, left, right) {
  10296. var pivot = items[Math.floor((right + left) / 2)];
  10297. while (left <= right) {
  10298. while (this._compare(items[left], pivot) < 0)
  10299. left++;
  10300. while (this._compare(items[right], pivot) > 0)
  10301. right--;
  10302. if (left < right) {
  10303. var temp = items[left];
  10304. items[left] = items[right];
  10305. items[right] = temp;
  10306. left++;
  10307. right--;
  10308. }
  10309. else if (left === right) {
  10310. left++;
  10311. break;
  10312. }
  10313. }
  10314. return left;
  10315. }
  10316. _quickSort(items, left, right) {
  10317. if (items.length > 1) {
  10318. var index = this._partition(items, left, right);
  10319. var leftIndex = index - 1;
  10320. if (left < leftIndex)
  10321. this._quickSort(items, left, leftIndex);
  10322. if (index < right)
  10323. this._quickSort(items, index, right);
  10324. }
  10325. }
  10326. _compare(left, right) {
  10327. throw "StaticBatch:must override this function.";
  10328. }
  10329. _initStaticBatchs(rootSprite) {
  10330. throw "StaticBatch:must override this function.";
  10331. }
  10332. _getBatchRenderElementFromPool() {
  10333. throw "StaticBatch:must override this function.";
  10334. }
  10335. _addBatchSprite(renderableSprite3D) {
  10336. this._initBatchSprites.push(renderableSprite3D);
  10337. }
  10338. _clear() {
  10339. this._batchRenderElementPoolIndex = 0;
  10340. }
  10341. _garbageCollection() {
  10342. throw "StaticBatchManager: must override it.";
  10343. }
  10344. dispose() {
  10345. this._staticBatches = null;
  10346. }
  10347. }
  10348. StaticBatchManager._managers = [];
  10349. class FrustumCulling {
  10350. constructor() {
  10351. }
  10352. static __init__() {
  10353. if (Laya.Render.supportWebGLPlusCulling) {
  10354. FrustumCulling._cullingBufferLength = 0;
  10355. FrustumCulling._cullingBuffer = new Float32Array(4096);
  10356. }
  10357. }
  10358. static _drawTraversalCullingBound(renderList, debugTool) {
  10359. var validCount = renderList.length;
  10360. var renders = renderList.elements;
  10361. for (var i = 0, n = renderList.length; i < n; i++) {
  10362. var color = FrustumCulling._tempColor0;
  10363. color.r = 0;
  10364. color.g = 1;
  10365. color.b = 0;
  10366. color.a = 1;
  10367. Utils3D._drawBound(debugTool, renders[i].bounds._getBoundBox(), color);
  10368. }
  10369. }
  10370. static _traversalCulling(camera, scene, context, renderList, customShader, replacementTag) {
  10371. var validCount = renderList.length;
  10372. var renders = renderList.elements;
  10373. var boundFrustum = camera.boundFrustum;
  10374. var camPos = camera._transform.position;
  10375. for (var i = 0; i < validCount; i++) {
  10376. var render = renders[i];
  10377. if (camera._isLayerVisible(render._owner._layer) && render._enable) {
  10378. Laya.Stat.frustumCulling++;
  10379. if (!camera.useOcclusionCulling || render._needRender(boundFrustum, context)) {
  10380. render._visible = true;
  10381. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  10382. var elements = render._renderElements;
  10383. for (var j = 0, m = elements.length; j < m; j++)
  10384. elements[j]._update(scene, context, customShader, replacementTag);
  10385. }
  10386. else {
  10387. render._visible = false;
  10388. }
  10389. }
  10390. else {
  10391. render._visible = false;
  10392. }
  10393. }
  10394. }
  10395. static renderObjectCulling(camera, scene, context, renderList, customShader, replacementTag) {
  10396. var i, n;
  10397. var opaqueQueue = scene._opaqueQueue;
  10398. var transparentQueue = scene._transparentQueue;
  10399. opaqueQueue.clear();
  10400. transparentQueue.clear();
  10401. var staticBatchManagers = StaticBatchManager._managers;
  10402. for (i = 0, n = staticBatchManagers.length; i < n; i++)
  10403. staticBatchManagers[i]._clear();
  10404. var dynamicBatchManagers = DynamicBatchManager._managers;
  10405. for (i = 0, n = dynamicBatchManagers.length; i < n; i++)
  10406. dynamicBatchManagers[i]._clear();
  10407. var octree = scene._octree;
  10408. if (octree) {
  10409. octree.updateMotionObjects();
  10410. octree.shrinkRootIfPossible();
  10411. octree.getCollidingWithFrustum(context, customShader, replacementTag);
  10412. }
  10413. FrustumCulling._traversalCulling(camera, scene, context, renderList, customShader, replacementTag);
  10414. if (FrustumCulling.debugFrustumCulling) {
  10415. var debugTool = scene._debugTool;
  10416. debugTool.clear();
  10417. if (octree) {
  10418. octree.drawAllBounds(debugTool);
  10419. octree.drawAllObjects(debugTool);
  10420. }
  10421. FrustumCulling._drawTraversalCullingBound(renderList, debugTool);
  10422. }
  10423. var count = opaqueQueue.elements.length;
  10424. (count > 0) && (opaqueQueue._quickSort(0, count - 1));
  10425. count = transparentQueue.elements.length;
  10426. (count > 0) && (transparentQueue._quickSort(0, count - 1));
  10427. }
  10428. static renderObjectCullingNative(camera, scene, context, renderList, customShader, replacementTag) {
  10429. var i, n, j, m;
  10430. var opaqueQueue = scene._opaqueQueue;
  10431. var transparentQueue = scene._transparentQueue;
  10432. opaqueQueue.clear();
  10433. transparentQueue.clear();
  10434. var staticBatchManagers = StaticBatchManager._managers;
  10435. for (i = 0, n = staticBatchManagers.length; i < n; i++)
  10436. staticBatchManagers[i]._clear();
  10437. var dynamicBatchManagers = DynamicBatchManager._managers;
  10438. for (i = 0, n = dynamicBatchManagers.length; i < n; i++)
  10439. dynamicBatchManagers[i]._clear();
  10440. var validCount = renderList.length;
  10441. var renders = renderList.elements;
  10442. for (i = 0; i < validCount; i++) {
  10443. renders[i].bounds;
  10444. renders[i]._updateForNative && renders[i]._updateForNative(context);
  10445. }
  10446. var boundFrustum = camera.boundFrustum;
  10447. FrustumCulling.cullingNative(camera._boundFrustumBuffer, FrustumCulling._cullingBuffer, scene._cullingBufferIndices, validCount, scene._cullingBufferResult);
  10448. var camPos = context.camera._transform.position;
  10449. for (i = 0; i < validCount; i++) {
  10450. var render = renders[i];
  10451. if (!camera.useOcclusionCulling || (camera._isLayerVisible(render._owner._layer) && render._enable && scene._cullingBufferResult[i])) {
  10452. render._visible = true;
  10453. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  10454. var elements = render._renderElements;
  10455. for (j = 0, m = elements.length; j < m; j++) {
  10456. var element = elements[j];
  10457. element._update(scene, context, customShader, replacementTag);
  10458. }
  10459. }
  10460. else {
  10461. render._visible = false;
  10462. }
  10463. }
  10464. var count = opaqueQueue.elements.length;
  10465. (count > 0) && (opaqueQueue._quickSort(0, count - 1));
  10466. count = transparentQueue.elements.length;
  10467. (count > 0) && (transparentQueue._quickSort(0, count - 1));
  10468. }
  10469. static cullingNative(boundFrustumBuffer, cullingBuffer, cullingBufferIndices, cullingCount, cullingBufferResult) {
  10470. return Laya.LayaGL.instance.culling(boundFrustumBuffer, cullingBuffer, cullingBufferIndices, cullingCount, cullingBufferResult);
  10471. }
  10472. }
  10473. FrustumCulling._tempVector3 = new Vector3();
  10474. FrustumCulling._tempColor0 = new Color();
  10475. FrustumCulling.debugFrustumCulling = false;
  10476. class BatchMark {
  10477. constructor() {
  10478. this.updateMark = -1;
  10479. this.indexInList = -1;
  10480. this.batched = false;
  10481. }
  10482. }
  10483. class GeometryElement {
  10484. constructor() {
  10485. this._destroyed = false;
  10486. }
  10487. get destroyed() {
  10488. return this._destroyed;
  10489. }
  10490. _getType() {
  10491. throw "GeometryElement:must override it.";
  10492. }
  10493. _prepareRender(state) {
  10494. return true;
  10495. }
  10496. _render(state) {
  10497. throw "GeometryElement:must override it.";
  10498. }
  10499. destroy() {
  10500. if (this._destroyed)
  10501. return;
  10502. this._destroyed = true;
  10503. }
  10504. }
  10505. GeometryElement._typeCounter = 0;
  10506. class VertexBuffer3D extends Laya.Buffer {
  10507. constructor(byteLength, bufferUsage, canRead = false) {
  10508. super();
  10509. this._vertexDeclaration = null;
  10510. this._float32Reader = null;
  10511. var gl = Laya.LayaGL.instance;
  10512. this._bufferUsage = bufferUsage;
  10513. this._bufferType = gl.ARRAY_BUFFER;
  10514. this._canRead = canRead;
  10515. this._byteLength = byteLength;
  10516. this.bind();
  10517. gl.bufferData(this._bufferType, this._byteLength, this._bufferUsage);
  10518. if (canRead) {
  10519. this._buffer = new Uint8Array(byteLength);
  10520. this._float32Reader = new Float32Array(this._buffer.buffer);
  10521. }
  10522. }
  10523. get vertexDeclaration() {
  10524. return this._vertexDeclaration;
  10525. }
  10526. set vertexDeclaration(value) {
  10527. this._vertexDeclaration = value;
  10528. }
  10529. get canRead() {
  10530. return this._canRead;
  10531. }
  10532. bind() {
  10533. if (Laya.Buffer._bindedVertexBuffer !== this._glBuffer) {
  10534. var gl = Laya.LayaGL.instance;
  10535. gl.bindBuffer(gl.ARRAY_BUFFER, this._glBuffer);
  10536. Laya.Buffer._bindedVertexBuffer = this._glBuffer;
  10537. return true;
  10538. }
  10539. else {
  10540. return false;
  10541. }
  10542. }
  10543. setData(buffer, bufferOffset = 0, dataStartIndex = 0, dataCount = Number.MAX_SAFE_INTEGER) {
  10544. this.bind();
  10545. var needSubData = dataStartIndex !== 0 || dataCount !== Number.MAX_SAFE_INTEGER;
  10546. if (needSubData) {
  10547. var subData = new Uint8Array(buffer, dataStartIndex, dataCount);
  10548. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset, subData);
  10549. if (this._canRead)
  10550. this._buffer.set(subData, bufferOffset);
  10551. }
  10552. else {
  10553. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset, buffer);
  10554. if (this._canRead)
  10555. this._buffer.set(new Uint8Array(buffer), bufferOffset);
  10556. }
  10557. }
  10558. getUint8Data() {
  10559. if (this._canRead)
  10560. return this._buffer;
  10561. else
  10562. throw new Error("Can't read data from VertexBuffer with only write flag!");
  10563. }
  10564. getFloat32Data() {
  10565. if (this._canRead)
  10566. return this._float32Reader;
  10567. else
  10568. throw new Error("Can't read data from VertexBuffer with only write flag!");
  10569. }
  10570. markAsUnreadbale() {
  10571. this._canRead = false;
  10572. this._buffer = null;
  10573. this._float32Reader = null;
  10574. }
  10575. destroy() {
  10576. super.destroy();
  10577. this._buffer = null;
  10578. this._float32Reader = null;
  10579. this._vertexDeclaration = null;
  10580. }
  10581. }
  10582. VertexBuffer3D.DATATYPE_FLOAT32ARRAY = 0;
  10583. VertexBuffer3D.DATATYPE_UINT8ARRAY = 1;
  10584. class VertexElementFormat {
  10585. static __init__() {
  10586. var gl = Laya.LayaGL.instance;
  10587. VertexElementFormat._elementInfos = {
  10588. "single": [1, gl.FLOAT, 0],
  10589. "vector2": [2, gl.FLOAT, 0],
  10590. "vector3": [3, gl.FLOAT, 0],
  10591. "vector4": [4, gl.FLOAT, 0],
  10592. "color": [4, gl.FLOAT, 0],
  10593. "byte4": [4, gl.UNSIGNED_BYTE, 0],
  10594. "short2": [2, gl.FLOAT, 0],
  10595. "short4": [4, gl.FLOAT, 0],
  10596. "normalizedshort2": [2, gl.FLOAT, 0],
  10597. "normalizedshort4": [4, gl.FLOAT, 0],
  10598. "halfvector2": [2, gl.FLOAT, 0],
  10599. "halfvector4": [4, gl.FLOAT, 0]
  10600. };
  10601. }
  10602. static getElementInfos(element) {
  10603. var info = VertexElementFormat._elementInfos[element];
  10604. if (info)
  10605. return info;
  10606. else
  10607. throw "VertexElementFormat: this vertexElementFormat is not implement.";
  10608. }
  10609. }
  10610. VertexElementFormat.Single = "single";
  10611. VertexElementFormat.Vector2 = "vector2";
  10612. VertexElementFormat.Vector3 = "vector3";
  10613. VertexElementFormat.Vector4 = "vector4";
  10614. VertexElementFormat.Color = "color";
  10615. VertexElementFormat.Byte4 = "byte4";
  10616. VertexElementFormat.Short2 = "short2";
  10617. VertexElementFormat.Short4 = "short4";
  10618. VertexElementFormat.NormalizedShort2 = "normalizedshort2";
  10619. VertexElementFormat.NormalizedShort4 = "normalizedshort4";
  10620. VertexElementFormat.HalfVector2 = "halfvector2";
  10621. VertexElementFormat.HalfVector4 = "halfvector4";
  10622. class VertexDeclaration {
  10623. constructor(vertexStride, vertexElements) {
  10624. this._id = ++VertexDeclaration._uniqueIDCounter;
  10625. this._vertexElementsDic = {};
  10626. this._vertexStride = vertexStride;
  10627. this._vertexElements = vertexElements;
  10628. var count = vertexElements.length;
  10629. this._shaderValues = new ShaderData(null);
  10630. for (var j = 0; j < count; j++) {
  10631. var vertexElement = vertexElements[j];
  10632. var name = vertexElement._elementUsage;
  10633. this._vertexElementsDic[name] = vertexElement;
  10634. var value = new Int32Array(5);
  10635. var elmentInfo = VertexElementFormat.getElementInfos(vertexElement._elementFormat);
  10636. value[0] = elmentInfo[0];
  10637. value[1] = elmentInfo[1];
  10638. value[2] = elmentInfo[2];
  10639. value[3] = this._vertexStride;
  10640. value[4] = vertexElement._offset;
  10641. this._shaderValues.setAttribute(name, value);
  10642. }
  10643. }
  10644. get id() {
  10645. return this._id;
  10646. }
  10647. get vertexStride() {
  10648. return this._vertexStride;
  10649. }
  10650. get vertexElementCount() {
  10651. return this._vertexElements.length;
  10652. }
  10653. getVertexElementByIndex(index) {
  10654. return this._vertexElements[index];
  10655. }
  10656. getVertexElementByUsage(usage) {
  10657. return this._vertexElementsDic[usage];
  10658. }
  10659. }
  10660. VertexDeclaration._uniqueIDCounter = 1;
  10661. class VertexElement {
  10662. get offset() {
  10663. return this._offset;
  10664. }
  10665. get elementFormat() {
  10666. return this._elementFormat;
  10667. }
  10668. get elementUsage() {
  10669. return this._elementUsage;
  10670. }
  10671. constructor(offset, elementFormat, elementUsage) {
  10672. this._offset = offset;
  10673. this._elementFormat = elementFormat;
  10674. this._elementUsage = elementUsage;
  10675. }
  10676. }
  10677. class VertexMesh {
  10678. static __init__() {
  10679. VertexMesh.instanceWorldMatrixDeclaration = new VertexDeclaration(64, [new VertexElement(0, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW0),
  10680. new VertexElement(16, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW1),
  10681. new VertexElement(32, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW2),
  10682. new VertexElement(48, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW3)]);
  10683. VertexMesh.instanceMVPMatrixDeclaration = new VertexDeclaration(64, [new VertexElement(0, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW0),
  10684. new VertexElement(16, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW1),
  10685. new VertexElement(32, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW2),
  10686. new VertexElement(48, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW3)]);
  10687. }
  10688. static getVertexDeclaration(vertexFlag, compatible = true) {
  10689. var verDec = VertexMesh._vertexDeclarationMap[vertexFlag + (compatible ? "_0" : "_1")];
  10690. if (!verDec) {
  10691. var subFlags = vertexFlag.split(",");
  10692. var offset = 0;
  10693. var elements = [];
  10694. for (var i = 0, n = subFlags.length; i < n; i++) {
  10695. var element;
  10696. switch (subFlags[i]) {
  10697. case "POSITION":
  10698. element = new VertexElement(offset, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0);
  10699. offset += 12;
  10700. break;
  10701. case "NORMAL":
  10702. element = new VertexElement(offset, VertexElementFormat.Vector3, VertexMesh.MESH_NORMAL0);
  10703. offset += 12;
  10704. break;
  10705. case "COLOR":
  10706. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_COLOR0);
  10707. offset += 16;
  10708. break;
  10709. case "UV":
  10710. element = new VertexElement(offset, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE0);
  10711. offset += 8;
  10712. break;
  10713. case "UV1":
  10714. element = new VertexElement(offset, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE1);
  10715. offset += 8;
  10716. break;
  10717. case "BLENDWEIGHT":
  10718. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_BLENDWEIGHT0);
  10719. offset += 16;
  10720. break;
  10721. case "BLENDINDICES":
  10722. if (compatible) {
  10723. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_BLENDINDICES0);
  10724. offset += 16;
  10725. }
  10726. else {
  10727. element = new VertexElement(offset, VertexElementFormat.Byte4, VertexMesh.MESH_BLENDINDICES0);
  10728. offset += 4;
  10729. }
  10730. break;
  10731. case "TANGENT":
  10732. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_TANGENT0);
  10733. offset += 16;
  10734. break;
  10735. default:
  10736. throw "VertexMesh: unknown vertex flag.";
  10737. }
  10738. elements.push(element);
  10739. }
  10740. verDec = new VertexDeclaration(offset, elements);
  10741. VertexMesh._vertexDeclarationMap[vertexFlag + (compatible ? "_0" : "_1")] = verDec;
  10742. }
  10743. return verDec;
  10744. }
  10745. }
  10746. VertexMesh.MESH_POSITION0 = 0;
  10747. VertexMesh.MESH_COLOR0 = 1;
  10748. VertexMesh.MESH_TEXTURECOORDINATE0 = 2;
  10749. VertexMesh.MESH_NORMAL0 = 3;
  10750. VertexMesh.MESH_TANGENT0 = 4;
  10751. VertexMesh.MESH_BLENDINDICES0 = 5;
  10752. VertexMesh.MESH_BLENDWEIGHT0 = 6;
  10753. VertexMesh.MESH_TEXTURECOORDINATE1 = 7;
  10754. VertexMesh.MESH_WORLDMATRIX_ROW0 = 8;
  10755. VertexMesh.MESH_WORLDMATRIX_ROW1 = 9;
  10756. VertexMesh.MESH_WORLDMATRIX_ROW2 = 10;
  10757. VertexMesh.MESH_WORLDMATRIX_ROW3 = 11;
  10758. VertexMesh.MESH_MVPMATRIX_ROW0 = 12;
  10759. VertexMesh.MESH_MVPMATRIX_ROW1 = 13;
  10760. VertexMesh.MESH_MVPMATRIX_ROW2 = 14;
  10761. VertexMesh.MESH_MVPMATRIX_ROW3 = 15;
  10762. VertexMesh._vertexDeclarationMap = {};
  10763. class SubMeshInstanceBatch extends GeometryElement {
  10764. constructor() {
  10765. super();
  10766. this.maxInstanceCount = 1024;
  10767. this.instanceWorldMatrixData = new Float32Array(this.maxInstanceCount * 16);
  10768. this.instanceMVPMatrixData = new Float32Array(this.maxInstanceCount * 16);
  10769. var gl = Laya.LayaGL.instance;
  10770. this.instanceWorldMatrixBuffer = new VertexBuffer3D(this.instanceWorldMatrixData.length * 4, gl.DYNAMIC_DRAW);
  10771. this.instanceMVPMatrixBuffer = new VertexBuffer3D(this.instanceMVPMatrixData.length * 4, gl.DYNAMIC_DRAW);
  10772. this.instanceWorldMatrixBuffer.vertexDeclaration = VertexMesh.instanceWorldMatrixDeclaration;
  10773. this.instanceMVPMatrixBuffer.vertexDeclaration = VertexMesh.instanceMVPMatrixDeclaration;
  10774. }
  10775. static __init__() {
  10776. SubMeshInstanceBatch.instance = new SubMeshInstanceBatch();
  10777. }
  10778. _render(state) {
  10779. var gl = Laya.LayaGL.instance;
  10780. var element = state.renderElement;
  10781. var subMesh = element.instanceSubMesh;
  10782. var count = element.instanceBatchElementList.length;
  10783. var indexCount = subMesh._indexCount;
  10784. subMesh._mesh._instanceBufferState.bind();
  10785. Laya.LayaGL.layaGPUInstance.drawElementsInstanced(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, subMesh._indexStart * 2, count);
  10786. Laya.Stat.renderBatches++;
  10787. Laya.Stat.savedRenderBatches += count - 1;
  10788. Laya.Stat.trianglesFaces += indexCount * count / 3;
  10789. }
  10790. }
  10791. class LightBound {
  10792. }
  10793. class ClusterData {
  10794. constructor() {
  10795. this.updateMark = -1;
  10796. this.pointLightCount = 0;
  10797. this.spotLightCount = 0;
  10798. this.indices = [];
  10799. }
  10800. }
  10801. class Cluster {
  10802. constructor(xSlices, ySlices, zSlices, maxLightsPerClusterAverage) {
  10803. this._updateMark = 0;
  10804. this._depthSliceParam = new Vector2();
  10805. this._xSlices = xSlices;
  10806. this._ySlices = ySlices;
  10807. this._zSlices = zSlices;
  10808. var clusterTexWidth = xSlices * ySlices;
  10809. var clisterTexHeight = zSlices * (1 + Math.ceil(maxLightsPerClusterAverage / 4));
  10810. this._clusterTexture = Utils3D._createFloatTextureBuffer(clusterTexWidth, clisterTexHeight);
  10811. this._clusterTexture.lock = true;
  10812. this._clusterPixels = new Float32Array(clusterTexWidth * clisterTexHeight * 4);
  10813. var clusterDatas = new Array(this._zSlices);
  10814. for (var z = 0; z < this._zSlices; z++) {
  10815. clusterDatas[z] = new Array(this._ySlices);
  10816. for (var y = 0; y < this._ySlices; y++) {
  10817. clusterDatas[z][y] = new Array(this._xSlices);
  10818. for (var x = 0; x < this._xSlices; x++)
  10819. clusterDatas[z][y][x] = new ClusterData();
  10820. }
  10821. }
  10822. this._clusterDatas = clusterDatas;
  10823. }
  10824. _insertSpotLightSphere(origin, forward, size, angle, testSphere) {
  10825. var V = Cluster._tempVector35;
  10826. V.x = testSphere.x - origin.x;
  10827. V.y = testSphere.y - origin.y;
  10828. V.z = testSphere.z - origin.z;
  10829. var VlenSq = Vector3.dot(V, V);
  10830. var sphereRadius = testSphere.w;
  10831. var rangeCull = VlenSq > sphereRadius * sphereRadius;
  10832. if (!rangeCull)
  10833. return false;
  10834. var V1len = Vector3.dot(V, forward);
  10835. var distanceClosestPoint = Math.cos(angle) * Math.sqrt(VlenSq - V1len * V1len) - V1len * Math.sin(angle);
  10836. var angleCull = distanceClosestPoint > sphereRadius;
  10837. var frontCull = V1len > sphereRadius + size;
  10838. var backCull = V1len < -sphereRadius;
  10839. return !(angleCull || frontCull || backCull);
  10840. }
  10841. _placePointLightToClusters(lightIndex, lightBound) {
  10842. var clusterDatas = this._clusterDatas;
  10843. var updateMark = this._updateMark;
  10844. for (var z = lightBound.zMin, zEnd = lightBound.zMax; z < zEnd; z++) {
  10845. for (var y = lightBound.yMin, yEnd = lightBound.yMax; y < yEnd; y++) {
  10846. for (var x = lightBound.xMin, xEnd = lightBound.xMax; x < xEnd; x++) {
  10847. var data = clusterDatas[z][y][x];
  10848. if (data.updateMark != updateMark) {
  10849. data.pointLightCount = 0;
  10850. data.spotLightCount = 0;
  10851. data.updateMark = updateMark;
  10852. }
  10853. var indices = data.indices;
  10854. var lightCount = data.pointLightCount++;
  10855. if (lightCount < indices.length)
  10856. indices[lightCount] = lightIndex;
  10857. else
  10858. indices.push(lightIndex);
  10859. }
  10860. }
  10861. }
  10862. }
  10863. _placeSpotLightToClusters(lightIndex, lightBound) {
  10864. var clusterDatas = this._clusterDatas;
  10865. var updateMark = this._updateMark;
  10866. for (var z = lightBound.zMin, zEnd = lightBound.zMax; z < zEnd; z++) {
  10867. for (var y = lightBound.yMin, yEnd = lightBound.yMax; y < yEnd; y++) {
  10868. for (var x = lightBound.xMin, xEnd = lightBound.xMax; x < xEnd; x++) {
  10869. var data = clusterDatas[z][y][x];
  10870. if (data.updateMark != updateMark) {
  10871. data.pointLightCount = 0;
  10872. data.spotLightCount = 0;
  10873. data.updateMark = updateMark;
  10874. }
  10875. var indices = data.indices;
  10876. var lightCount = data.pointLightCount + data.spotLightCount++;
  10877. if (lightCount < indices.length)
  10878. indices[lightCount] = lightIndex;
  10879. else
  10880. indices.push(lightIndex);
  10881. }
  10882. }
  10883. }
  10884. }
  10885. _insertConePlane(origin, forward, radius, halfAngle, pNor) {
  10886. var V1 = Cluster._tempVector36;
  10887. var V2 = Cluster._tempVector37;
  10888. Vector3.cross(pNor, forward, V1);
  10889. Vector3.cross(V1, forward, V2);
  10890. Vector3.normalize(V2, V2);
  10891. var tanR = radius * Math.tan(halfAngle);
  10892. var capRimX = origin.x + radius * forward.x + tanR * V2.x;
  10893. var capRimY = origin.y + radius * forward.y + tanR * V2.y;
  10894. var capRimZ = origin.z + radius * forward.z + tanR * V2.z;
  10895. return capRimX * pNor.x + capRimY * pNor.y + capRimZ * pNor.z <= 0 || origin.x * pNor.x + origin.y * pNor.y + origin.z * pNor.z <= 0;
  10896. }
  10897. _shrinkSphereLightZPerspective(near, far, lightviewPos, radius, lightBound) {
  10898. var lvZ = lightviewPos.z;
  10899. var minZ = lvZ - radius;
  10900. var maxZ = lvZ + radius;
  10901. if ((minZ > far) || (maxZ <= near))
  10902. return false;
  10903. var depthSliceParam = this._depthSliceParam;
  10904. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  10905. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  10906. return true;
  10907. }
  10908. _shrinkSpotLightZPerspective(near, far, viewLightPos, viewConeCap, radius, halfAngle, lightBound) {
  10909. var pbX = viewConeCap.x, pbY = viewConeCap.y, pbZ = viewConeCap.z;
  10910. var rb = Math.tan(halfAngle) * radius;
  10911. var paX = viewLightPos.x, paY = viewLightPos.y, paZ = viewLightPos.z;
  10912. var aX = pbX - paX, aY = pbY - paY, aZ = pbZ - paZ;
  10913. var dotA = aX * aX + aY * aY + aZ * aZ;
  10914. var eZ = Math.sqrt(1.0 - aZ * aZ / dotA);
  10915. var minZ = Math.max(Math.min(paZ, pbZ - eZ * rb), viewLightPos.z - radius);
  10916. var maxZ = Math.min(Math.max(paZ, pbZ + eZ * rb), viewLightPos.z + radius);
  10917. if ((minZ > far) || (maxZ <= near))
  10918. return false;
  10919. var depthSliceParam = this._depthSliceParam;
  10920. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  10921. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  10922. return true;
  10923. }
  10924. _shrinkSphereLightByBoundOrth(halfX, halfY, near, far, lightviewPos, radius, lightBound) {
  10925. var lvZ = lightviewPos.z;
  10926. var minZ = lvZ - radius, maxZ = lvZ + radius;
  10927. if ((minZ > far) || (maxZ <= near))
  10928. return false;
  10929. var lvX = lightviewPos.x;
  10930. var minX = lvX - radius, maxX = lvX + radius;
  10931. if ((minX > halfX) || (maxX <= -halfX))
  10932. return false;
  10933. var lvY = lightviewPos.y;
  10934. var minY = lvY - radius, maxY = lvY + radius;
  10935. if ((minY > halfY) || (maxY <= -halfY))
  10936. return false;
  10937. var xSlices = this._xSlices, ySlices = this._ySlices;
  10938. var depthSliceParam = this._depthSliceParam;
  10939. var xStride = halfX * 2 / xSlices, yStride = halfY * 2 / ySlices;
  10940. lightBound.xMin = Math.max(Math.floor((minX + halfX) / xStride), 0);
  10941. lightBound.xMax = Math.min(Math.ceil((maxX + halfX) / xStride), xSlices);
  10942. lightBound.yMin = Math.max(Math.floor((halfY - maxY) / yStride), 0);
  10943. lightBound.yMax = Math.min(Math.ceil((halfY - minY) / yStride), ySlices);
  10944. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  10945. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  10946. return true;
  10947. }
  10948. _shrinkSpotLightByBoundOrth(halfX, halfY, near, far, viewLightPos, viewConeCap, radius, halfAngle, lightBound) {
  10949. var pbX = viewConeCap.x, pbY = viewConeCap.y, pbZ = viewConeCap.z;
  10950. var rb = Math.tan(halfAngle) * radius;
  10951. var paX = viewLightPos.x, paY = viewLightPos.y, paZ = viewLightPos.z;
  10952. var aX = pbX - paX, aY = pbY - paY, aZ = pbZ - paZ;
  10953. var dotA = aX * aX + aY * aY + aZ * aZ;
  10954. var eZ = Math.sqrt(1.0 - aZ * aZ / dotA);
  10955. var minZ = Math.max(Math.min(paZ, pbZ - eZ * rb), viewLightPos.z - radius);
  10956. var maxZ = Math.min(Math.max(paZ, pbZ + eZ * rb), viewLightPos.z + radius);
  10957. if ((minZ > far) || (maxZ <= near))
  10958. return false;
  10959. var eX = Math.sqrt(1.0 - aX * aX / dotA);
  10960. var minX = Math.max(Math.min(paX, pbX - eX * rb), viewLightPos.x - radius);
  10961. var maxX = Math.min(Math.max(paX, pbX + eX * rb), viewLightPos.x + radius);
  10962. if ((minX > halfX) || (maxX <= -halfX))
  10963. return false;
  10964. var eY = Math.sqrt(1.0 - aY * aY / dotA);
  10965. var minY = Math.max(Math.min(paY, pbY - eY * rb), viewLightPos.y - radius);
  10966. var maxY = Math.min(Math.max(paY, pbY + eY * rb), viewLightPos.y + radius);
  10967. if ((minY > halfY) || (maxY <= -halfY))
  10968. return false;
  10969. var xSlices = this._xSlices, ySlices = this._ySlices;
  10970. var depthSliceParam = this._depthSliceParam;
  10971. var xStride = halfX * 2 / xSlices, yStride = halfY * 2 / ySlices;
  10972. lightBound.xMin = Math.max(Math.floor((minX + halfX) / xStride), 0);
  10973. lightBound.xMax = Math.min(Math.ceil((maxX + halfX) / xStride), xSlices);
  10974. lightBound.yMin = Math.max(Math.floor((halfY - maxY) / yStride), 0);
  10975. lightBound.yMax = Math.min(Math.ceil((halfY - minY) / yStride), ySlices);
  10976. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  10977. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  10978. return true;
  10979. }
  10980. _shrinkXYByRadiusPerspective(lightviewPos, radius, lightBound, xPlanes, yPlanes) {
  10981. var xMin, yMin;
  10982. var xMax, yMax;
  10983. var lvX = lightviewPos.x, lvY = lightviewPos.y, lvZ = lightviewPos.z;
  10984. var i;
  10985. var n = this._ySlices + 1;
  10986. for (i = 0; i < n; i++) {
  10987. var plane = yPlanes[i];
  10988. if (lvY * plane.y + lvZ * plane.z < radius) {
  10989. yMin = Math.max(0, i - 1);
  10990. break;
  10991. }
  10992. }
  10993. if (i == n)
  10994. return false;
  10995. yMax = this._ySlices;
  10996. for (i = yMin + 1; i < n; i++) {
  10997. var plane = yPlanes[i];
  10998. if (lvY * plane.y + lvZ * plane.z <= -radius) {
  10999. yMax = Math.max(0, i);
  11000. break;
  11001. }
  11002. }
  11003. n = this._xSlices + 1;
  11004. for (i = 0; i < n; i++) {
  11005. var plane = xPlanes[i];
  11006. if (lvX * plane.x + lvZ * plane.z < radius) {
  11007. xMin = Math.max(0, i - 1);
  11008. break;
  11009. }
  11010. }
  11011. xMax = this._xSlices;
  11012. for (i = xMin + 1; i < n; i++) {
  11013. var plane = xPlanes[i];
  11014. if (lvX * plane.x + lvZ * plane.z <= -radius) {
  11015. xMax = Math.max(0, i);
  11016. break;
  11017. }
  11018. }
  11019. lightBound.xMin = xMin;
  11020. lightBound.xMax = xMax;
  11021. lightBound.yMin = yMin;
  11022. lightBound.yMax = yMax;
  11023. return true;
  11024. }
  11025. _shrinkSpotXYByConePerspective(lightviewPos, viewForward, radius, halfAngle, lightBound, xPlanes, yPlanes) {
  11026. var xMin, yMin;
  11027. var xMax, yMax;
  11028. var normal = Cluster._tempVector32;
  11029. var n = lightBound.yMax + 1;
  11030. for (var i = lightBound.yMin + 1; i < n; i++) {
  11031. if (this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, yPlanes[i])) {
  11032. yMin = Math.max(0, i - 1);
  11033. break;
  11034. }
  11035. }
  11036. yMax = lightBound.yMax;
  11037. for (var i = yMin + 1; i < n; i++) {
  11038. var plane = yPlanes[i];
  11039. normal.setValue(0, -plane.y, -plane.z);
  11040. if (!this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, normal)) {
  11041. yMax = Math.max(0, i);
  11042. break;
  11043. }
  11044. }
  11045. n = lightBound.xMax + 1;
  11046. for (var i = lightBound.xMin + 1; i < n; i++) {
  11047. if (this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, xPlanes[i])) {
  11048. xMin = Math.max(0, i - 1);
  11049. break;
  11050. }
  11051. }
  11052. xMax = lightBound.xMax;
  11053. for (var i = xMin + 1; i < n; i++) {
  11054. var plane = xPlanes[i];
  11055. normal.setValue(-plane.x, 0, -plane.z);
  11056. if (!this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, normal)) {
  11057. xMax = Math.max(0, i);
  11058. break;
  11059. }
  11060. }
  11061. lightBound.xMin = xMin;
  11062. lightBound.xMax = xMax;
  11063. lightBound.yMin = yMin;
  11064. lightBound.yMax = yMax;
  11065. }
  11066. _updatePointLightPerspective(near, far, viewMat, pointLight, lightIndex, xPlanes, yPlanes) {
  11067. var lightBound = Cluster._tempLightBound;
  11068. var lightviewPos = Cluster._tempVector30;
  11069. Vector3.transformV3ToV3(pointLight._transform.position, viewMat, lightviewPos);
  11070. lightviewPos.z *= -1;
  11071. if (!this._shrinkSphereLightZPerspective(near, far, lightviewPos, pointLight.range, lightBound))
  11072. return;
  11073. if (!this._shrinkXYByRadiusPerspective(lightviewPos, pointLight.range, lightBound, xPlanes, yPlanes))
  11074. return;
  11075. this._placePointLightToClusters(lightIndex, lightBound);
  11076. }
  11077. _updateSpotLightPerspective(near, far, viewMat, spotLight, lightIndex, xPlanes, yPlanes) {
  11078. var lightBound = Cluster._tempLightBound;
  11079. var viewPos = Cluster._tempVector30;
  11080. var forward = Cluster._tempVector31;
  11081. var viewConeCap = Cluster._tempVector34;
  11082. var position = spotLight._transform.position;
  11083. var range = spotLight.range;
  11084. spotLight._transform.worldMatrix.getForward(forward);
  11085. Vector3.normalize(forward, forward);
  11086. Vector3.scale(forward, range, viewConeCap);
  11087. Vector3.add(position, viewConeCap, viewConeCap);
  11088. Vector3.transformV3ToV3(position, viewMat, viewPos);
  11089. Vector3.transformV3ToV3(viewConeCap, viewMat, viewConeCap);
  11090. viewPos.z *= -1;
  11091. viewConeCap.z *= -1;
  11092. var halfAngle = (spotLight.spotAngle / 2) * Math.PI / 180;
  11093. if (!this._shrinkSpotLightZPerspective(near, far, viewPos, viewConeCap, range, halfAngle, lightBound))
  11094. return;
  11095. if (!this._shrinkXYByRadiusPerspective(viewPos, range, lightBound, xPlanes, yPlanes))
  11096. return;
  11097. var viewFor = Cluster._tempVector33;
  11098. viewFor.x = viewConeCap.x - viewPos.x, viewFor.y = viewConeCap.y - viewPos.y, viewFor.z = viewConeCap.z - viewPos.z;
  11099. Vector3.normalize(viewFor, viewFor);
  11100. this._shrinkSpotXYByConePerspective(viewPos, viewFor, range, halfAngle, lightBound, xPlanes, yPlanes);
  11101. this._placeSpotLightToClusters(lightIndex, lightBound);
  11102. }
  11103. _updatePointLightOrth(halfX, halfY, near, far, viewMat, pointLight, lightIndex) {
  11104. var lightBound = Cluster._tempLightBound;
  11105. var lightviewPos = Cluster._tempVector30;
  11106. Vector3.transformV3ToV3(pointLight._transform.position, viewMat, lightviewPos);
  11107. lightviewPos.z *= -1;
  11108. if (!this._shrinkSphereLightByBoundOrth(halfX, halfY, near, far, lightviewPos, pointLight.range, lightBound))
  11109. return;
  11110. this._placePointLightToClusters(lightIndex, lightBound);
  11111. }
  11112. _updateSpotLightOrth(halfX, halfY, near, far, viewMat, spotLight, lightIndex) {
  11113. var lightBound = Cluster._tempLightBound;
  11114. var viewPos = Cluster._tempVector30;
  11115. var forward = Cluster._tempVector31;
  11116. var viewConeCap = Cluster._tempVector34;
  11117. var position = spotLight._transform.position;
  11118. var range = spotLight.range;
  11119. spotLight._transform.worldMatrix.getForward(forward);
  11120. Vector3.normalize(forward, forward);
  11121. Vector3.scale(forward, range, viewConeCap);
  11122. Vector3.add(position, viewConeCap, viewConeCap);
  11123. Vector3.transformV3ToV3(position, viewMat, viewPos);
  11124. Vector3.transformV3ToV3(viewConeCap, viewMat, viewConeCap);
  11125. viewPos.z *= -1;
  11126. viewConeCap.z *= -1;
  11127. var halfAngle = (spotLight.spotAngle / 2) * Math.PI / 180;
  11128. if (!this._shrinkSpotLightByBoundOrth(halfX, halfY, near, far, viewPos, viewConeCap, range, halfAngle, lightBound))
  11129. return;
  11130. this._placeSpotLightToClusters(lightIndex, lightBound);
  11131. }
  11132. update(camera, scene) {
  11133. this._updateMark++;
  11134. var camNear = camera.nearPlane;
  11135. this._depthSliceParam.x = Config3D._config.lightClusterCount.z / Math.log2(camera.farPlane / camNear);
  11136. this._depthSliceParam.y = Math.log2(camNear) * this._depthSliceParam.x;
  11137. var near = camera.nearPlane;
  11138. var far = camera.farPlane;
  11139. var viewMat = camera.viewMatrix;
  11140. var curCount = scene._directionLights._length;
  11141. var pointLights = scene._pointLights;
  11142. var poiCount = pointLights._length;
  11143. var poiElements = pointLights._elements;
  11144. var spotLights = scene._spotLights;
  11145. var spoCount = spotLights._length;
  11146. var spoElements = spotLights._elements;
  11147. if (camera.orthographic) {
  11148. var halfY = camera.orthographicVerticalSize / 2.0;
  11149. var halfX = halfY * camera.aspectRatio;
  11150. for (var i = 0; i < poiCount; i++, curCount++)
  11151. this._updatePointLightOrth(halfX, halfY, near, far, viewMat, poiElements[i], curCount);
  11152. for (var i = 0; i < spoCount; i++, curCount++)
  11153. this._updateSpotLightOrth(halfX, halfY, near, far, viewMat, spoElements[i], curCount);
  11154. }
  11155. else {
  11156. camera._updateClusterPlaneXY();
  11157. var xPlanes = camera._clusterXPlanes;
  11158. var yPlanes = camera._clusterYPlanes;
  11159. for (var i = 0; i < poiCount; i++, curCount++)
  11160. this._updatePointLightPerspective(near, far, viewMat, poiElements[i], curCount, xPlanes, yPlanes);
  11161. for (var i = 0; i < spoCount; i++, curCount++)
  11162. this._updateSpotLightPerspective(near, far, viewMat, spoElements[i], curCount, xPlanes, yPlanes);
  11163. }
  11164. if (poiCount + spoCount > 0) {
  11165. var xSlices = this._xSlices, ySlices = this._ySlices, zSlices = this._zSlices;
  11166. var widthFloat = xSlices * ySlices * 4;
  11167. var lightOff = widthFloat * zSlices;
  11168. var clusterPixels = this._clusterPixels;
  11169. var clusterPixelsCount = clusterPixels.length;
  11170. var clusterDatas = this._clusterDatas;
  11171. var updateMark = this._updateMark;
  11172. var freeSpace = true;
  11173. for (var z = 0; z < zSlices; z++) {
  11174. for (var y = 0; y < ySlices; y++) {
  11175. for (var x = 0; x < xSlices; x++) {
  11176. var data = clusterDatas[z][y][x];
  11177. var clusterOff = (x + y * xSlices + z * xSlices * ySlices) * 4;
  11178. if (data.updateMark !== updateMark) {
  11179. clusterPixels[clusterOff] = 0;
  11180. clusterPixels[clusterOff + 1] = 0;
  11181. }
  11182. else {
  11183. if (freeSpace) {
  11184. var indices = data.indices;
  11185. var pCount = data.pointLightCount;
  11186. var sCount = data.spotLightCount;
  11187. var count = pCount + sCount;
  11188. if (lightOff + count < clusterPixelsCount) {
  11189. clusterPixels[clusterOff] = pCount;
  11190. clusterPixels[clusterOff + 1] = sCount;
  11191. clusterPixels[clusterOff + 2] = Math.floor(lightOff / widthFloat);
  11192. clusterPixels[clusterOff + 3] = lightOff % widthFloat;
  11193. for (var i = 0; i < count; i++)
  11194. clusterPixels[lightOff++] = indices[i];
  11195. }
  11196. else {
  11197. count = clusterPixelsCount - (lightOff + count);
  11198. pCount = Math.min(pCount, count);
  11199. clusterPixels[clusterOff] = pCount;
  11200. clusterPixels[clusterOff + 1] = Math.min(sCount, count - pCount);
  11201. clusterPixels[clusterOff + 2] = Math.floor(lightOff / widthFloat);
  11202. clusterPixels[clusterOff + 3] = lightOff % widthFloat;
  11203. for (var i = 0; i < count; i++)
  11204. clusterPixels[lightOff++] = indices[i];
  11205. freeSpace = false;
  11206. }
  11207. }
  11208. }
  11209. }
  11210. }
  11211. }
  11212. var width = this._clusterTexture.width;
  11213. this._clusterTexture.setSubPixels(0, 0, width, Math.ceil(lightOff / (4 * width)), clusterPixels);
  11214. }
  11215. }
  11216. }
  11217. Cluster._tempVector30 = new Vector3();
  11218. Cluster._tempVector31 = new Vector3();
  11219. Cluster._tempVector32 = new Vector3();
  11220. Cluster._tempVector33 = new Vector3();
  11221. Cluster._tempVector34 = new Vector3();
  11222. Cluster._tempVector35 = new Vector3();
  11223. Cluster._tempVector36 = new Vector3();
  11224. Cluster._tempVector37 = new Vector3();
  11225. Cluster._tempLightBound = new LightBound();
  11226. class Plane {
  11227. constructor(normal, d = 0) {
  11228. this.normal = normal;
  11229. this.distance = d;
  11230. }
  11231. static createPlaneBy3P(point1, point2, point3) {
  11232. var x1 = point2.x - point1.x;
  11233. var y1 = point2.y - point1.y;
  11234. var z1 = point2.z - point1.z;
  11235. var x2 = point3.x - point1.x;
  11236. var y2 = point3.y - point1.y;
  11237. var z2 = point3.z - point1.z;
  11238. var yz = (y1 * z2) - (z1 * y2);
  11239. var xz = (z1 * x2) - (x1 * z2);
  11240. var xy = (x1 * y2) - (y1 * x2);
  11241. var invPyth = 1 / (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  11242. var x = yz * invPyth;
  11243. var y = xz * invPyth;
  11244. var z = xy * invPyth;
  11245. Plane._TEMPVec3.x = x;
  11246. Plane._TEMPVec3.y = y;
  11247. Plane._TEMPVec3.z = z;
  11248. var d = -((x * point1.x) + (y * point1.y) + (z * point1.z));
  11249. var plane = new Plane(Plane._TEMPVec3, d);
  11250. return plane;
  11251. }
  11252. normalize() {
  11253. var normalEX = this.normal.x;
  11254. var normalEY = this.normal.y;
  11255. var normalEZ = this.normal.z;
  11256. var magnitude = 1 / Math.sqrt(normalEX * normalEX + normalEY * normalEY + normalEZ * normalEZ);
  11257. this.normal.x = normalEX * magnitude;
  11258. this.normal.y = normalEY * magnitude;
  11259. this.normal.z = normalEZ * magnitude;
  11260. this.distance *= magnitude;
  11261. }
  11262. }
  11263. Plane._TEMPVec3 = new Vector3();
  11264. Plane.PlaneIntersectionType_Back = 0;
  11265. Plane.PlaneIntersectionType_Front = 1;
  11266. Plane.PlaneIntersectionType_Intersecting = 2;
  11267. class Ray {
  11268. constructor(origin, direction) {
  11269. this.origin = origin;
  11270. this.direction = direction;
  11271. }
  11272. }
  11273. class ContainmentType {
  11274. }
  11275. ContainmentType.Disjoint = 0;
  11276. ContainmentType.Contains = 1;
  11277. ContainmentType.Intersects = 2;
  11278. class CollisionUtils {
  11279. constructor() {
  11280. }
  11281. static distancePlaneToPoint(plane, point) {
  11282. var dot = Vector3.dot(plane.normal, point);
  11283. return dot - plane.distance;
  11284. }
  11285. static distanceBoxToPoint(box, point) {
  11286. var boxMin = box.min;
  11287. var boxMineX = boxMin.x;
  11288. var boxMineY = boxMin.y;
  11289. var boxMineZ = boxMin.z;
  11290. var boxMax = box.max;
  11291. var boxMaxeX = boxMax.x;
  11292. var boxMaxeY = boxMax.y;
  11293. var boxMaxeZ = boxMax.z;
  11294. var pointeX = point.x;
  11295. var pointeY = point.y;
  11296. var pointeZ = point.z;
  11297. var distance = 0;
  11298. if (pointeX < boxMineX)
  11299. distance += (boxMineX - pointeX) * (boxMineX - pointeX);
  11300. if (pointeX > boxMaxeX)
  11301. distance += (boxMaxeX - pointeX) * (boxMaxeX - pointeX);
  11302. if (pointeY < boxMineY)
  11303. distance += (boxMineY - pointeY) * (boxMineY - pointeY);
  11304. if (pointeY > boxMaxeY)
  11305. distance += (boxMaxeY - pointeY) * (boxMaxeY - pointeY);
  11306. if (pointeZ < boxMineZ)
  11307. distance += (boxMineZ - pointeZ) * (boxMineZ - pointeZ);
  11308. if (pointeZ > boxMaxeZ)
  11309. distance += (boxMaxeZ - pointeZ) * (boxMaxeZ - pointeZ);
  11310. return Math.sqrt(distance);
  11311. }
  11312. static distanceBoxToBox(box1, box2) {
  11313. var box1Mine = box1.min;
  11314. var box1MineX = box1Mine.x;
  11315. var box1MineY = box1Mine.y;
  11316. var box1MineZ = box1Mine.z;
  11317. var box1Maxe = box1.max;
  11318. var box1MaxeX = box1Maxe.x;
  11319. var box1MaxeY = box1Maxe.y;
  11320. var box1MaxeZ = box1Maxe.z;
  11321. var box2Mine = box2.min;
  11322. var box2MineX = box2Mine.x;
  11323. var box2MineY = box2Mine.y;
  11324. var box2MineZ = box2Mine.z;
  11325. var box2Maxe = box2.max;
  11326. var box2MaxeX = box2Maxe.x;
  11327. var box2MaxeY = box2Maxe.y;
  11328. var box2MaxeZ = box2Maxe.z;
  11329. var distance = 0;
  11330. var delta;
  11331. if (box1MineX > box2MaxeX) {
  11332. delta = box1MineX - box2MaxeX;
  11333. distance += delta * delta;
  11334. }
  11335. else if (box2MineX > box1MaxeX) {
  11336. delta = box2MineX - box1MaxeX;
  11337. distance += delta * delta;
  11338. }
  11339. if (box1MineY > box2MaxeY) {
  11340. delta = box1MineY - box2MaxeY;
  11341. distance += delta * delta;
  11342. }
  11343. else if (box2MineY > box1MaxeY) {
  11344. delta = box2MineY - box1MaxeY;
  11345. distance += delta * delta;
  11346. }
  11347. if (box1MineZ > box2MaxeZ) {
  11348. delta = box1MineZ - box2MaxeZ;
  11349. distance += delta * delta;
  11350. }
  11351. else if (box2MineZ > box1MaxeZ) {
  11352. delta = box2MineZ - box1MaxeZ;
  11353. distance += delta * delta;
  11354. }
  11355. return Math.sqrt(distance);
  11356. }
  11357. static distanceSphereToPoint(sphere, point) {
  11358. var distance = Math.sqrt(Vector3.distanceSquared(sphere.center, point));
  11359. distance -= sphere.radius;
  11360. return Math.max(distance, 0);
  11361. }
  11362. static distanceSphereToSphere(sphere1, sphere2) {
  11363. var distance = Math.sqrt(Vector3.distanceSquared(sphere1.center, sphere2.center));
  11364. distance -= sphere1.radius + sphere2.radius;
  11365. return Math.max(distance, 0);
  11366. }
  11367. static intersectsRayAndTriangleRD(ray, vertex1, vertex2, vertex3, out) {
  11368. var rayO = ray.origin;
  11369. var rayOeX = rayO.x;
  11370. var rayOeY = rayO.y;
  11371. var rayOeZ = rayO.z;
  11372. var rayD = ray.direction;
  11373. var rayDeX = rayD.x;
  11374. var rayDeY = rayD.y;
  11375. var rayDeZ = rayD.z;
  11376. var v1eX = vertex1.x;
  11377. var v1eY = vertex1.y;
  11378. var v1eZ = vertex1.z;
  11379. var v2eX = vertex2.x;
  11380. var v2eY = vertex2.y;
  11381. var v2eZ = vertex2.z;
  11382. var v3eX = vertex3.x;
  11383. var v3eY = vertex3.y;
  11384. var v3eZ = vertex3.z;
  11385. var _tempV30eX = CollisionUtils._tempV30.x;
  11386. var _tempV30eY = CollisionUtils._tempV30.y;
  11387. var _tempV30eZ = CollisionUtils._tempV30.z;
  11388. _tempV30eX = v2eX - v1eX;
  11389. _tempV30eY = v2eY - v1eY;
  11390. _tempV30eZ = v2eZ - v1eZ;
  11391. var _tempV31eX = CollisionUtils._tempV31.x;
  11392. var _tempV31eY = CollisionUtils._tempV31.y;
  11393. var _tempV31eZ = CollisionUtils._tempV31.z;
  11394. _tempV31eX = v3eX - v1eX;
  11395. _tempV31eY = v3eY - v1eY;
  11396. _tempV31eZ = v3eZ - v1eZ;
  11397. var _tempV32eX = CollisionUtils._tempV32.x;
  11398. var _tempV32eY = CollisionUtils._tempV32.y;
  11399. var _tempV32eZ = CollisionUtils._tempV32.z;
  11400. _tempV32eX = (rayDeY * _tempV31eZ) - (rayDeZ * _tempV31eY);
  11401. _tempV32eY = (rayDeZ * _tempV31eX) - (rayDeX * _tempV31eZ);
  11402. _tempV32eZ = (rayDeX * _tempV31eY) - (rayDeY * _tempV31eX);
  11403. var determinant = (_tempV30eX * _tempV32eX) + (_tempV30eY * _tempV32eY) + (_tempV30eZ * _tempV32eZ);
  11404. if (MathUtils3D.isZero(determinant)) {
  11405. return false;
  11406. }
  11407. var inversedeterminant = 1 / determinant;
  11408. var _tempV33eX = CollisionUtils._tempV33.x;
  11409. var _tempV33eY = CollisionUtils._tempV33.y;
  11410. var _tempV33eZ = CollisionUtils._tempV33.z;
  11411. _tempV33eX = rayOeX - v1eX;
  11412. _tempV33eY = rayOeY - v1eY;
  11413. _tempV33eZ = rayOeZ - v1eZ;
  11414. var triangleU = (_tempV33eX * _tempV32eX) + (_tempV33eY * _tempV32eY) + (_tempV33eZ * _tempV32eZ);
  11415. triangleU *= inversedeterminant;
  11416. if (triangleU < 0 || triangleU > 1) {
  11417. return false;
  11418. }
  11419. var _tempV34eX = CollisionUtils._tempV34.x;
  11420. var _tempV34eY = CollisionUtils._tempV34.y;
  11421. var _tempV34eZ = CollisionUtils._tempV34.z;
  11422. _tempV34eX = (_tempV33eY * _tempV30eZ) - (_tempV33eZ * _tempV30eY);
  11423. _tempV34eY = (_tempV33eZ * _tempV30eX) - (_tempV33eX * _tempV30eZ);
  11424. _tempV34eZ = (_tempV33eX * _tempV30eY) - (_tempV33eY * _tempV30eX);
  11425. var triangleV = ((rayDeX * _tempV34eX) + (rayDeY * _tempV34eY)) + (rayDeZ * _tempV34eZ);
  11426. triangleV *= inversedeterminant;
  11427. if (triangleV < 0 || triangleU + triangleV > 1) {
  11428. return false;
  11429. }
  11430. var raydistance = (_tempV31eX * _tempV34eX) + (_tempV31eY * _tempV34eY) + (_tempV31eZ * _tempV34eZ);
  11431. raydistance *= inversedeterminant;
  11432. if (raydistance < 0) {
  11433. return false;
  11434. }
  11435. return true;
  11436. }
  11437. static intersectsRayAndTriangleRP(ray, vertex1, vertex2, vertex3, out) {
  11438. var distance;
  11439. if (!CollisionUtils.intersectsRayAndTriangleRD(ray, vertex1, vertex2, vertex3, distance)) {
  11440. out = Vector3._ZERO;
  11441. return false;
  11442. }
  11443. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  11444. Vector3.add(ray.origin, CollisionUtils._tempV30, out);
  11445. return true;
  11446. }
  11447. static intersectsRayAndPoint(ray, point) {
  11448. Vector3.subtract(ray.origin, point, CollisionUtils._tempV30);
  11449. var b = Vector3.dot(CollisionUtils._tempV30, ray.direction);
  11450. var c = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30) - MathUtils3D.zeroTolerance;
  11451. if (c > 0 && b > 0)
  11452. return false;
  11453. var discriminant = b * b - c;
  11454. if (discriminant < 0)
  11455. return false;
  11456. return true;
  11457. }
  11458. static intersectsRayAndRay(ray1, ray2, out) {
  11459. var ray1o = ray1.origin;
  11460. var ray1oeX = ray1o.x;
  11461. var ray1oeY = ray1o.y;
  11462. var ray1oeZ = ray1o.z;
  11463. var ray1d = ray1.direction;
  11464. var ray1deX = ray1d.x;
  11465. var ray1deY = ray1d.y;
  11466. var ray1deZ = ray1d.z;
  11467. var ray2o = ray2.origin;
  11468. var ray2oeX = ray2o.x;
  11469. var ray2oeY = ray2o.y;
  11470. var ray2oeZ = ray2o.z;
  11471. var ray2d = ray2.direction;
  11472. var ray2deX = ray2d.x;
  11473. var ray2deY = ray2d.y;
  11474. var ray2deZ = ray2d.z;
  11475. Vector3.cross(ray1d, ray2d, CollisionUtils._tempV30);
  11476. var tempV3 = CollisionUtils._tempV30;
  11477. var denominator = Vector3.scalarLength(CollisionUtils._tempV30);
  11478. if (MathUtils3D.isZero(denominator)) {
  11479. if (MathUtils3D.nearEqual(ray2oeX, ray1oeX) && MathUtils3D.nearEqual(ray2oeY, ray1oeY) && MathUtils3D.nearEqual(ray2oeZ, ray1oeZ)) {
  11480. return true;
  11481. }
  11482. }
  11483. denominator = denominator * denominator;
  11484. var m11 = ray2oeX - ray1oeX;
  11485. var m12 = ray2oeY - ray1oeY;
  11486. var m13 = ray2oeZ - ray1oeZ;
  11487. var m21 = ray2deX;
  11488. var m22 = ray2deY;
  11489. var m23 = ray2deZ;
  11490. var m31 = tempV3.x;
  11491. var m32 = tempV3.y;
  11492. var m33 = tempV3.z;
  11493. var dets = m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32 - m11 * m23 * m32 - m12 * m21 * m33 - m13 * m22 * m31;
  11494. m21 = ray1deX;
  11495. m22 = ray1deY;
  11496. m23 = ray1deZ;
  11497. var s = dets / denominator;
  11498. Vector3.scale(ray1d, s, CollisionUtils._tempV30);
  11499. Vector3.scale(ray2d, s, CollisionUtils._tempV31);
  11500. Vector3.add(ray1o, CollisionUtils._tempV30, CollisionUtils._tempV32);
  11501. Vector3.add(ray2o, CollisionUtils._tempV31, CollisionUtils._tempV33);
  11502. var point1e = CollisionUtils._tempV32;
  11503. var point2e = CollisionUtils._tempV33;
  11504. if (!MathUtils3D.nearEqual(point2e.x, point1e.x) || !MathUtils3D.nearEqual(point2e.y, point1e.y) || !MathUtils3D.nearEqual(point2e.z, point1e.z)) {
  11505. return false;
  11506. }
  11507. return true;
  11508. }
  11509. static intersectsPlaneAndTriangle(plane, vertex1, vertex2, vertex3) {
  11510. var test1 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex1);
  11511. var test2 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex2);
  11512. var test3 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex3);
  11513. if (test1 == Plane.PlaneIntersectionType_Front && test2 == Plane.PlaneIntersectionType_Front && test3 == Plane.PlaneIntersectionType_Front)
  11514. return Plane.PlaneIntersectionType_Front;
  11515. if (test1 == Plane.PlaneIntersectionType_Back && test2 == Plane.PlaneIntersectionType_Back && test3 == Plane.PlaneIntersectionType_Back)
  11516. return Plane.PlaneIntersectionType_Back;
  11517. return Plane.PlaneIntersectionType_Intersecting;
  11518. }
  11519. static intersectsRayAndPlaneRD(ray, plane, out) {
  11520. var planeNor = plane.normal;
  11521. var direction = Vector3.dot(planeNor, ray.direction);
  11522. if (MathUtils3D.isZero(direction)) {
  11523. out = 0;
  11524. return false;
  11525. }
  11526. var position = Vector3.dot(planeNor, ray.origin);
  11527. out = (-plane.distance - position) / direction;
  11528. if (out < 0) {
  11529. out = 0;
  11530. return false;
  11531. }
  11532. return true;
  11533. }
  11534. static intersectsRayAndPlaneRP(ray, plane, out) {
  11535. var distance;
  11536. if (!CollisionUtils.intersectsRayAndPlaneRD(ray, plane, distance)) {
  11537. return false;
  11538. }
  11539. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  11540. Vector3.add(ray.origin, CollisionUtils._tempV30, CollisionUtils._tempV31);
  11541. return true;
  11542. }
  11543. static intersectsRayAndBoxRD(ray, box) {
  11544. var rayoe = ray.origin;
  11545. var rayoeX = rayoe.x;
  11546. var rayoeY = rayoe.y;
  11547. var rayoeZ = rayoe.z;
  11548. var rayde = ray.direction;
  11549. var raydeX = rayde.x;
  11550. var raydeY = rayde.y;
  11551. var raydeZ = rayde.z;
  11552. var boxMine = box.min;
  11553. var boxMineX = boxMine.x;
  11554. var boxMineY = boxMine.y;
  11555. var boxMineZ = boxMine.z;
  11556. var boxMaxe = box.max;
  11557. var boxMaxeX = boxMaxe.x;
  11558. var boxMaxeY = boxMaxe.y;
  11559. var boxMaxeZ = boxMaxe.z;
  11560. var out = 0;
  11561. var tmax = MathUtils3D.MaxValue;
  11562. if (MathUtils3D.isZero(raydeX)) {
  11563. if (rayoeX < boxMineX || rayoeX > boxMaxeX) {
  11564. return -1;
  11565. }
  11566. }
  11567. else {
  11568. var inverse = 1 / raydeX;
  11569. var t1 = (boxMineX - rayoeX) * inverse;
  11570. var t2 = (boxMaxeX - rayoeX) * inverse;
  11571. if (t1 > t2) {
  11572. var temp = t1;
  11573. t1 = t2;
  11574. t2 = temp;
  11575. }
  11576. out = Math.max(t1, out);
  11577. tmax = Math.min(t2, tmax);
  11578. if (out > tmax) {
  11579. return -1;
  11580. }
  11581. }
  11582. if (MathUtils3D.isZero(raydeY)) {
  11583. if (rayoeY < boxMineY || rayoeY > boxMaxeY) {
  11584. return -1;
  11585. }
  11586. }
  11587. else {
  11588. var inverse1 = 1 / raydeY;
  11589. var t3 = (boxMineY - rayoeY) * inverse1;
  11590. var t4 = (boxMaxeY - rayoeY) * inverse1;
  11591. if (t3 > t4) {
  11592. var temp1 = t3;
  11593. t3 = t4;
  11594. t4 = temp1;
  11595. }
  11596. out = Math.max(t3, out);
  11597. tmax = Math.min(t4, tmax);
  11598. if (out > tmax) {
  11599. return -1;
  11600. }
  11601. }
  11602. if (MathUtils3D.isZero(raydeZ)) {
  11603. if (rayoeZ < boxMineZ || rayoeZ > boxMaxeZ) {
  11604. return -1;
  11605. }
  11606. }
  11607. else {
  11608. var inverse2 = 1 / raydeZ;
  11609. var t5 = (boxMineZ - rayoeZ) * inverse2;
  11610. var t6 = (boxMaxeZ - rayoeZ) * inverse2;
  11611. if (t5 > t6) {
  11612. var temp2 = t5;
  11613. t5 = t6;
  11614. t6 = temp2;
  11615. }
  11616. out = Math.max(t5, out);
  11617. tmax = Math.min(t6, tmax);
  11618. if (out > tmax) {
  11619. return -1;
  11620. }
  11621. }
  11622. return out;
  11623. }
  11624. static intersectsRayAndBoxRP(ray, box, out) {
  11625. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, box);
  11626. if (distance === -1) {
  11627. Vector3._ZERO.cloneTo(out);
  11628. return distance;
  11629. }
  11630. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  11631. Vector3.add(ray.origin, CollisionUtils._tempV30, CollisionUtils._tempV31);
  11632. CollisionUtils._tempV31.cloneTo(out);
  11633. return distance;
  11634. }
  11635. static intersectsRayAndSphereRD(ray, sphere) {
  11636. var sphereR = sphere.radius;
  11637. Vector3.subtract(ray.origin, sphere.center, CollisionUtils._tempV30);
  11638. var b = Vector3.dot(CollisionUtils._tempV30, ray.direction);
  11639. var c = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30) - (sphereR * sphereR);
  11640. if (c > 0 && b > 0) {
  11641. return -1;
  11642. }
  11643. var discriminant = b * b - c;
  11644. if (discriminant < 0) {
  11645. return -1;
  11646. }
  11647. var distance = -b - Math.sqrt(discriminant);
  11648. if (distance < 0)
  11649. distance = 0;
  11650. return distance;
  11651. }
  11652. static intersectsRayAndSphereRP(ray, sphere, out) {
  11653. var distance = CollisionUtils.intersectsRayAndSphereRD(ray, sphere);
  11654. if (distance === -1) {
  11655. Vector3._ZERO.cloneTo(out);
  11656. return distance;
  11657. }
  11658. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  11659. Vector3.add(ray.origin, CollisionUtils._tempV30, CollisionUtils._tempV31);
  11660. CollisionUtils._tempV31.cloneTo(out);
  11661. return distance;
  11662. }
  11663. static intersectsSphereAndTriangle(sphere, vertex1, vertex2, vertex3) {
  11664. var sphereC = sphere.center;
  11665. var sphereR = sphere.radius;
  11666. CollisionUtils.closestPointPointTriangle(sphereC, vertex1, vertex2, vertex3, CollisionUtils._tempV30);
  11667. Vector3.subtract(CollisionUtils._tempV30, sphereC, CollisionUtils._tempV31);
  11668. var dot = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV31);
  11669. return dot <= sphereR * sphereR;
  11670. }
  11671. static intersectsPlaneAndPoint(plane, point) {
  11672. var distance = Vector3.dot(plane.normal, point) + plane.distance;
  11673. if (distance > 0)
  11674. return Plane.PlaneIntersectionType_Front;
  11675. if (distance < 0)
  11676. return Plane.PlaneIntersectionType_Back;
  11677. return Plane.PlaneIntersectionType_Intersecting;
  11678. }
  11679. static intersectsPlaneAndPlane(plane1, plane2) {
  11680. Vector3.cross(plane1.normal, plane2.normal, CollisionUtils._tempV30);
  11681. var denominator = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30);
  11682. if (MathUtils3D.isZero(denominator))
  11683. return false;
  11684. return true;
  11685. }
  11686. static intersectsPlaneAndPlaneRL(plane1, plane2, line) {
  11687. var plane1nor = plane1.normal;
  11688. var plane2nor = plane2.normal;
  11689. Vector3.cross(plane1nor, plane2nor, CollisionUtils._tempV34);
  11690. var denominator = Vector3.dot(CollisionUtils._tempV34, CollisionUtils._tempV34);
  11691. if (MathUtils3D.isZero(denominator))
  11692. return false;
  11693. Vector3.scale(plane2nor, plane1.distance, CollisionUtils._tempV30);
  11694. Vector3.scale(plane1nor, plane2.distance, CollisionUtils._tempV31);
  11695. Vector3.subtract(CollisionUtils._tempV30, CollisionUtils._tempV31, CollisionUtils._tempV32);
  11696. Vector3.cross(CollisionUtils._tempV32, CollisionUtils._tempV34, CollisionUtils._tempV33);
  11697. Vector3.normalize(CollisionUtils._tempV34, CollisionUtils._tempV34);
  11698. return true;
  11699. }
  11700. static intersectsPlaneAndBox(plane, box) {
  11701. var planeD = plane.distance;
  11702. var planeNor = plane.normal;
  11703. var planeNoreX = planeNor.x;
  11704. var planeNoreY = planeNor.y;
  11705. var planeNoreZ = planeNor.z;
  11706. var boxMine = box.min;
  11707. var boxMineX = boxMine.x;
  11708. var boxMineY = boxMine.y;
  11709. var boxMineZ = boxMine.z;
  11710. var boxMaxe = box.max;
  11711. var boxMaxeX = boxMaxe.x;
  11712. var boxMaxeY = boxMaxe.y;
  11713. var boxMaxeZ = boxMaxe.z;
  11714. CollisionUtils._tempV30.x = (planeNoreX > 0) ? boxMineX : boxMaxeX;
  11715. CollisionUtils._tempV30.y = (planeNoreY > 0) ? boxMineY : boxMaxeY;
  11716. CollisionUtils._tempV30.z = (planeNoreZ > 0) ? boxMineZ : boxMaxeZ;
  11717. CollisionUtils._tempV31.x = (planeNoreX > 0) ? boxMaxeX : boxMineX;
  11718. CollisionUtils._tempV31.y = (planeNoreY > 0) ? boxMaxeY : boxMineY;
  11719. CollisionUtils._tempV31.z = (planeNoreZ > 0) ? boxMaxeZ : boxMineZ;
  11720. var distance = Vector3.dot(planeNor, CollisionUtils._tempV30);
  11721. if (distance + planeD > 0)
  11722. return Plane.PlaneIntersectionType_Front;
  11723. distance = Vector3.dot(planeNor, CollisionUtils._tempV31);
  11724. if (distance + planeD < 0)
  11725. return Plane.PlaneIntersectionType_Back;
  11726. return Plane.PlaneIntersectionType_Intersecting;
  11727. }
  11728. static intersectsPlaneAndSphere(plane, sphere) {
  11729. var sphereR = sphere.radius;
  11730. var distance = Vector3.dot(plane.normal, sphere.center) + plane.distance;
  11731. if (distance > sphereR)
  11732. return Plane.PlaneIntersectionType_Front;
  11733. if (distance < -sphereR)
  11734. return Plane.PlaneIntersectionType_Back;
  11735. return Plane.PlaneIntersectionType_Intersecting;
  11736. }
  11737. static intersectsBoxAndBox(box1, box2) {
  11738. var box1Mine = box1.min;
  11739. var box1Maxe = box1.max;
  11740. var box2Mine = box2.min;
  11741. var box2Maxe = box2.max;
  11742. if (box1Mine.x > box2Maxe.x || box2Mine.x > box1Maxe.x)
  11743. return false;
  11744. if (box1Mine.y > box2Maxe.y || box2Mine.y > box1Maxe.y)
  11745. return false;
  11746. if (box1Mine.z > box2Maxe.z || box2Mine.z > box1Maxe.z)
  11747. return false;
  11748. return true;
  11749. }
  11750. static intersectsBoxAndSphere(box, sphere) {
  11751. var sphereC = sphere.center;
  11752. var sphereR = sphere.radius;
  11753. Vector3.Clamp(sphereC, box.min, box.max, CollisionUtils._tempV30);
  11754. var distance = Vector3.distanceSquared(sphereC, CollisionUtils._tempV30);
  11755. return distance <= sphereR * sphereR;
  11756. }
  11757. static intersectsSphereAndSphere(sphere1, sphere2) {
  11758. var radiisum = sphere1.radius + sphere2.radius;
  11759. return Vector3.distanceSquared(sphere1.center, sphere2.center) <= radiisum * radiisum;
  11760. }
  11761. static boxContainsPoint(box, point) {
  11762. var boxMine = box.min;
  11763. var boxMaxe = box.max;
  11764. 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)
  11765. return ContainmentType.Contains;
  11766. return ContainmentType.Disjoint;
  11767. }
  11768. static boxContainsBox(box1, box2) {
  11769. var box1Mine = box1.min;
  11770. var box1MineX = box1Mine.x;
  11771. var box1MineY = box1Mine.y;
  11772. var box1MineZ = box1Mine.z;
  11773. var box1Maxe = box1.max;
  11774. var box1MaxeX = box1Maxe.x;
  11775. var box1MaxeY = box1Maxe.y;
  11776. var box1MaxeZ = box1Maxe.z;
  11777. var box2Mine = box2.min;
  11778. var box2MineX = box2Mine.x;
  11779. var box2MineY = box2Mine.y;
  11780. var box2MineZ = box2Mine.z;
  11781. var box2Maxe = box2.max;
  11782. var box2MaxeX = box2Maxe.x;
  11783. var box2MaxeY = box2Maxe.y;
  11784. var box2MaxeZ = box2Maxe.z;
  11785. if (box1MaxeX < box2MineX || box1MineX > box2MaxeX)
  11786. return ContainmentType.Disjoint;
  11787. if (box1MaxeY < box2MineY || box1MineY > box2MaxeY)
  11788. return ContainmentType.Disjoint;
  11789. if (box1MaxeZ < box2MineZ || box1MineZ > box2MaxeZ)
  11790. return ContainmentType.Disjoint;
  11791. if (box1MineX <= box2MineX && box2MaxeX <= box1MaxeX && box1MineY <= box2MineY && box2MaxeY <= box1MaxeY && box1MineZ <= box2MineZ && box2MaxeZ <= box1MaxeZ) {
  11792. return ContainmentType.Contains;
  11793. }
  11794. return ContainmentType.Intersects;
  11795. }
  11796. static boxContainsSphere(box, sphere) {
  11797. var boxMin = box.min;
  11798. var boxMineX = boxMin.x;
  11799. var boxMineY = boxMin.y;
  11800. var boxMineZ = boxMin.z;
  11801. var boxMax = box.max;
  11802. var boxMaxeX = boxMax.x;
  11803. var boxMaxeY = boxMax.y;
  11804. var boxMaxeZ = boxMax.z;
  11805. var sphereC = sphere.center;
  11806. var sphereCeX = sphereC.x;
  11807. var sphereCeY = sphereC.y;
  11808. var sphereCeZ = sphereC.z;
  11809. var sphereR = sphere.radius;
  11810. Vector3.Clamp(sphereC, boxMin, boxMax, CollisionUtils._tempV30);
  11811. var distance = Vector3.distanceSquared(sphereC, CollisionUtils._tempV30);
  11812. if (distance > sphereR * sphereR)
  11813. return ContainmentType.Disjoint;
  11814. if ((((boxMineX + sphereR <= sphereCeX) && (sphereCeX <= boxMaxeX - sphereR)) && ((boxMaxeX - boxMineX > sphereR) &&
  11815. (boxMineY + sphereR <= sphereCeY))) && (((sphereCeY <= boxMaxeY - sphereR) && (boxMaxeY - boxMineY > sphereR)) &&
  11816. (((boxMineZ + sphereR <= sphereCeZ) && (sphereCeZ <= boxMaxeZ - sphereR)) && (boxMaxeZ - boxMineZ > sphereR))))
  11817. return ContainmentType.Contains;
  11818. return ContainmentType.Intersects;
  11819. }
  11820. static sphereContainsPoint(sphere, point) {
  11821. if (Vector3.distanceSquared(point, sphere.center) <= sphere.radius * sphere.radius)
  11822. return ContainmentType.Contains;
  11823. return ContainmentType.Disjoint;
  11824. }
  11825. static sphereContainsTriangle(sphere, vertex1, vertex2, vertex3) {
  11826. var test1 = CollisionUtils.sphereContainsPoint(sphere, vertex1);
  11827. var test2 = CollisionUtils.sphereContainsPoint(sphere, vertex2);
  11828. var test3 = CollisionUtils.sphereContainsPoint(sphere, vertex3);
  11829. if (test1 == ContainmentType.Contains && test2 == ContainmentType.Contains && test3 == ContainmentType.Contains)
  11830. return ContainmentType.Contains;
  11831. if (CollisionUtils.intersectsSphereAndTriangle(sphere, vertex1, vertex2, vertex3))
  11832. return ContainmentType.Intersects;
  11833. return ContainmentType.Disjoint;
  11834. }
  11835. static sphereContainsBox(sphere, box) {
  11836. var sphereC = sphere.center;
  11837. var sphereCeX = sphereC.x;
  11838. var sphereCeY = sphereC.y;
  11839. var sphereCeZ = sphereC.z;
  11840. var sphereR = sphere.radius;
  11841. var boxMin = box.min;
  11842. var boxMineX = boxMin.x;
  11843. var boxMineY = boxMin.y;
  11844. var boxMineZ = boxMin.z;
  11845. var boxMax = box.max;
  11846. var boxMaxeX = boxMax.x;
  11847. var boxMaxeY = boxMax.y;
  11848. var boxMaxeZ = boxMax.z;
  11849. var _tempV30e = CollisionUtils._tempV30;
  11850. var _tempV30eX = _tempV30e.x;
  11851. var _tempV30eY = _tempV30e.y;
  11852. var _tempV30eZ = _tempV30e.z;
  11853. if (!CollisionUtils.intersectsBoxAndSphere(box, sphere))
  11854. return ContainmentType.Disjoint;
  11855. var radiusSquared = sphereR * sphereR;
  11856. _tempV30eX = sphereCeX - boxMineX;
  11857. _tempV30eY = sphereCeY - boxMaxeY;
  11858. _tempV30eZ = sphereCeZ - boxMaxeZ;
  11859. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11860. return ContainmentType.Intersects;
  11861. _tempV30eX = sphereCeX - boxMaxeX;
  11862. _tempV30eY = sphereCeY - boxMaxeY;
  11863. _tempV30eZ = sphereCeZ - boxMaxeZ;
  11864. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11865. return ContainmentType.Intersects;
  11866. _tempV30eX = sphereCeX - boxMaxeX;
  11867. _tempV30eY = sphereCeY - boxMineY;
  11868. _tempV30eZ = sphereCeZ - boxMaxeZ;
  11869. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11870. return ContainmentType.Intersects;
  11871. _tempV30eX = sphereCeX - boxMineX;
  11872. _tempV30eY = sphereCeY - boxMineY;
  11873. _tempV30eZ = sphereCeZ - boxMaxeZ;
  11874. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11875. return ContainmentType.Intersects;
  11876. _tempV30eX = sphereCeX - boxMineX;
  11877. _tempV30eY = sphereCeY - boxMaxeY;
  11878. _tempV30eZ = sphereCeZ - boxMineZ;
  11879. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11880. return ContainmentType.Intersects;
  11881. _tempV30eX = sphereCeX - boxMaxeX;
  11882. _tempV30eY = sphereCeY - boxMaxeY;
  11883. _tempV30eZ = sphereCeZ - boxMineZ;
  11884. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11885. return ContainmentType.Intersects;
  11886. _tempV30eX = sphereCeX - boxMaxeX;
  11887. _tempV30eY = sphereCeY - boxMineY;
  11888. _tempV30eZ = sphereCeZ - boxMineZ;
  11889. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11890. return ContainmentType.Intersects;
  11891. _tempV30eX = sphereCeX - boxMineX;
  11892. _tempV30eY = sphereCeY - boxMineY;
  11893. _tempV30eZ = sphereCeZ - boxMineZ;
  11894. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11895. return ContainmentType.Intersects;
  11896. return ContainmentType.Contains;
  11897. }
  11898. static sphereContainsSphere(sphere1, sphere2) {
  11899. var sphere1R = sphere1.radius;
  11900. var sphere2R = sphere2.radius;
  11901. var distance = Vector3.distance(sphere1.center, sphere2.center);
  11902. if (sphere1R + sphere2R < distance)
  11903. return ContainmentType.Disjoint;
  11904. if (sphere1R - sphere2R < distance)
  11905. return ContainmentType.Intersects;
  11906. return ContainmentType.Contains;
  11907. }
  11908. static closestPointPointTriangle(point, vertex1, vertex2, vertex3, out) {
  11909. Vector3.subtract(vertex2, vertex1, CollisionUtils._tempV30);
  11910. Vector3.subtract(vertex3, vertex1, CollisionUtils._tempV31);
  11911. Vector3.subtract(point, vertex1, CollisionUtils._tempV32);
  11912. Vector3.subtract(point, vertex2, CollisionUtils._tempV33);
  11913. Vector3.subtract(point, vertex3, CollisionUtils._tempV34);
  11914. var d1 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV32);
  11915. var d2 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV32);
  11916. var d3 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV33);
  11917. var d4 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV33);
  11918. var d5 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV34);
  11919. var d6 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV34);
  11920. if (d1 <= 0 && d2 <= 0) {
  11921. vertex1.cloneTo(out);
  11922. return;
  11923. }
  11924. if (d3 >= 0 && d4 <= d3) {
  11925. vertex2.cloneTo(out);
  11926. return;
  11927. }
  11928. var vc = d1 * d4 - d3 * d2;
  11929. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  11930. var v = d1 / (d1 - d3);
  11931. Vector3.scale(CollisionUtils._tempV30, v, out);
  11932. Vector3.add(vertex1, out, out);
  11933. return;
  11934. }
  11935. if (d6 >= 0 && d5 <= d6) {
  11936. vertex3.cloneTo(out);
  11937. return;
  11938. }
  11939. var vb = d5 * d2 - d1 * d6;
  11940. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  11941. var w = d2 / (d2 - d6);
  11942. Vector3.scale(CollisionUtils._tempV31, w, out);
  11943. Vector3.add(vertex1, out, out);
  11944. return;
  11945. }
  11946. var va = d3 * d6 - d5 * d4;
  11947. if (va <= 0 && (d4 - d3) >= 0 && (d5 - d6) >= 0) {
  11948. var w3 = (d4 - d3) / ((d4 - d3) + (d5 - d6));
  11949. Vector3.subtract(vertex3, vertex2, out);
  11950. Vector3.scale(out, w3, out);
  11951. Vector3.add(vertex2, out, out);
  11952. return;
  11953. }
  11954. var denom = 1 / (va + vb + vc);
  11955. var v2 = vb * denom;
  11956. var w2 = vc * denom;
  11957. Vector3.scale(CollisionUtils._tempV30, v2, CollisionUtils._tempV35);
  11958. Vector3.scale(CollisionUtils._tempV31, w2, CollisionUtils._tempV36);
  11959. Vector3.add(CollisionUtils._tempV35, CollisionUtils._tempV36, out);
  11960. Vector3.add(vertex1, out, out);
  11961. }
  11962. static closestPointPlanePoint(plane, point, out) {
  11963. var planeN = plane.normal;
  11964. var t = Vector3.dot(planeN, point) - plane.distance;
  11965. Vector3.scale(planeN, t, CollisionUtils._tempV30);
  11966. Vector3.subtract(point, CollisionUtils._tempV30, out);
  11967. }
  11968. static closestPointBoxPoint(box, point, out) {
  11969. Vector3.max(point, box.min, CollisionUtils._tempV30);
  11970. Vector3.min(CollisionUtils._tempV30, box.max, out);
  11971. }
  11972. static closestPointSpherePoint(sphere, point, out) {
  11973. var sphereC = sphere.center;
  11974. Vector3.subtract(point, sphereC, out);
  11975. Vector3.normalize(out, out);
  11976. Vector3.scale(out, sphere.radius, out);
  11977. Vector3.add(out, sphereC, out);
  11978. }
  11979. static closestPointSphereSphere(sphere1, sphere2, out) {
  11980. var sphere1C = sphere1.center;
  11981. Vector3.subtract(sphere2.center, sphere1C, out);
  11982. Vector3.normalize(out, out);
  11983. Vector3.scale(out, sphere1.radius, out);
  11984. Vector3.add(out, sphere1C, out);
  11985. }
  11986. }
  11987. CollisionUtils._tempV30 = new Vector3();
  11988. CollisionUtils._tempV31 = new Vector3();
  11989. CollisionUtils._tempV32 = new Vector3();
  11990. CollisionUtils._tempV33 = new Vector3();
  11991. CollisionUtils._tempV34 = new Vector3();
  11992. CollisionUtils._tempV35 = new Vector3();
  11993. CollisionUtils._tempV36 = new Vector3();
  11994. class BoundFrustum {
  11995. constructor(matrix) {
  11996. this._matrix = matrix;
  11997. this._near = new Plane(new Vector3());
  11998. this._far = new Plane(new Vector3());
  11999. this._left = new Plane(new Vector3());
  12000. this._right = new Plane(new Vector3());
  12001. this._top = new Plane(new Vector3());
  12002. this._bottom = new Plane(new Vector3());
  12003. BoundFrustum._getPlanesFromMatrix(this._matrix, this._near, this._far, this._left, this._right, this._top, this._bottom);
  12004. }
  12005. get matrix() {
  12006. return this._matrix;
  12007. }
  12008. set matrix(matrix) {
  12009. this._matrix = matrix;
  12010. BoundFrustum._getPlanesFromMatrix(this._matrix, this._near, this._far, this._left, this._right, this._top, this._bottom);
  12011. }
  12012. get near() {
  12013. return this._near;
  12014. }
  12015. get far() {
  12016. return this._far;
  12017. }
  12018. get left() {
  12019. return this._left;
  12020. }
  12021. get right() {
  12022. return this._right;
  12023. }
  12024. get top() {
  12025. return this._top;
  12026. }
  12027. get bottom() {
  12028. return this._bottom;
  12029. }
  12030. equalsBoundFrustum(other) {
  12031. return this._matrix.equalsOtherMatrix(other.matrix);
  12032. }
  12033. equalsObj(obj) {
  12034. if (obj instanceof BoundFrustum) {
  12035. var bf = obj;
  12036. return this.equalsBoundFrustum(bf);
  12037. }
  12038. return false;
  12039. }
  12040. getPlane(index) {
  12041. switch (index) {
  12042. case 0:
  12043. return this._near;
  12044. case 1:
  12045. return this._far;
  12046. case 2:
  12047. return this._left;
  12048. case 3:
  12049. return this._right;
  12050. case 4:
  12051. return this._top;
  12052. case 5:
  12053. return this._bottom;
  12054. default:
  12055. return null;
  12056. }
  12057. }
  12058. static _getPlanesFromMatrix(m, np, fp, lp, rp, tp, bp) {
  12059. var matrixE = m.elements;
  12060. var m11 = matrixE[0];
  12061. var m12 = matrixE[1];
  12062. var m13 = matrixE[2];
  12063. var m14 = matrixE[3];
  12064. var m21 = matrixE[4];
  12065. var m22 = matrixE[5];
  12066. var m23 = matrixE[6];
  12067. var m24 = matrixE[7];
  12068. var m31 = matrixE[8];
  12069. var m32 = matrixE[9];
  12070. var m33 = matrixE[10];
  12071. var m34 = matrixE[11];
  12072. var m41 = matrixE[12];
  12073. var m42 = matrixE[13];
  12074. var m43 = matrixE[14];
  12075. var m44 = matrixE[15];
  12076. var nearNorE = np.normal;
  12077. nearNorE.x = m14 + m13;
  12078. nearNorE.y = m24 + m23;
  12079. nearNorE.z = m34 + m33;
  12080. np.distance = m44 + m43;
  12081. np.normalize();
  12082. var farNorE = fp.normal;
  12083. farNorE.x = m14 - m13;
  12084. farNorE.y = m24 - m23;
  12085. farNorE.z = m34 - m33;
  12086. fp.distance = m44 - m43;
  12087. fp.normalize();
  12088. var leftNorE = lp.normal;
  12089. leftNorE.x = m14 + m11;
  12090. leftNorE.y = m24 + m21;
  12091. leftNorE.z = m34 + m31;
  12092. lp.distance = m44 + m41;
  12093. lp.normalize();
  12094. var rightNorE = rp.normal;
  12095. rightNorE.x = m14 - m11;
  12096. rightNorE.y = m24 - m21;
  12097. rightNorE.z = m34 - m31;
  12098. rp.distance = m44 - m41;
  12099. rp.normalize();
  12100. var topNorE = tp.normal;
  12101. topNorE.x = m14 - m12;
  12102. topNorE.y = m24 - m22;
  12103. topNorE.z = m34 - m32;
  12104. tp.distance = m44 - m42;
  12105. tp.normalize();
  12106. var bottomNorE = bp.normal;
  12107. bottomNorE.x = m14 + m12;
  12108. bottomNorE.y = m24 + m22;
  12109. bottomNorE.z = m34 + m32;
  12110. bp.distance = m44 + m42;
  12111. bp.normalize();
  12112. }
  12113. static _get3PlaneInterPoint(p1, p2, p3) {
  12114. var p1Nor = p1.normal;
  12115. var p2Nor = p2.normal;
  12116. var p3Nor = p3.normal;
  12117. Vector3.cross(p2Nor, p3Nor, BoundFrustum._tempV30);
  12118. Vector3.cross(p3Nor, p1Nor, BoundFrustum._tempV31);
  12119. Vector3.cross(p1Nor, p2Nor, BoundFrustum._tempV32);
  12120. var a = Vector3.dot(p1Nor, BoundFrustum._tempV30);
  12121. var b = Vector3.dot(p2Nor, BoundFrustum._tempV31);
  12122. var c = Vector3.dot(p3Nor, BoundFrustum._tempV32);
  12123. Vector3.scale(BoundFrustum._tempV30, -p1.distance / a, BoundFrustum._tempV33);
  12124. Vector3.scale(BoundFrustum._tempV31, -p2.distance / b, BoundFrustum._tempV34);
  12125. Vector3.scale(BoundFrustum._tempV32, -p3.distance / c, BoundFrustum._tempV35);
  12126. Vector3.add(BoundFrustum._tempV33, BoundFrustum._tempV34, BoundFrustum._tempV36);
  12127. Vector3.add(BoundFrustum._tempV35, BoundFrustum._tempV36, BoundFrustum._tempV37);
  12128. var v = BoundFrustum._tempV37;
  12129. return v;
  12130. }
  12131. getCorners(corners) {
  12132. BoundFrustum._get3PlaneInterPoint(this._near, this._bottom, this._right).cloneTo(corners[0]);
  12133. BoundFrustum._get3PlaneInterPoint(this._near, this._top, this._right).cloneTo(corners[1]);
  12134. BoundFrustum._get3PlaneInterPoint(this._near, this._top, this._left).cloneTo(corners[2]);
  12135. BoundFrustum._get3PlaneInterPoint(this._near, this._bottom, this._left).cloneTo(corners[3]);
  12136. BoundFrustum._get3PlaneInterPoint(this._far, this._bottom, this._right).cloneTo(corners[4]);
  12137. BoundFrustum._get3PlaneInterPoint(this._far, this._top, this._right).cloneTo(corners[5]);
  12138. BoundFrustum._get3PlaneInterPoint(this._far, this._top, this._left).cloneTo(corners[6]);
  12139. BoundFrustum._get3PlaneInterPoint(this._far, this._bottom, this._left).cloneTo(corners[7]);
  12140. }
  12141. containsPoint(point) {
  12142. var result = Plane.PlaneIntersectionType_Front;
  12143. var planeResult = Plane.PlaneIntersectionType_Front;
  12144. for (var i = 0; i < 6; i++) {
  12145. switch (i) {
  12146. case 0:
  12147. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._near, point);
  12148. break;
  12149. case 1:
  12150. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._far, point);
  12151. break;
  12152. case 2:
  12153. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._left, point);
  12154. break;
  12155. case 3:
  12156. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._right, point);
  12157. break;
  12158. case 4:
  12159. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._top, point);
  12160. break;
  12161. case 5:
  12162. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._bottom, point);
  12163. break;
  12164. }
  12165. switch (planeResult) {
  12166. case Plane.PlaneIntersectionType_Back:
  12167. return ContainmentType.Disjoint;
  12168. case Plane.PlaneIntersectionType_Intersecting:
  12169. result = Plane.PlaneIntersectionType_Intersecting;
  12170. break;
  12171. }
  12172. }
  12173. switch (result) {
  12174. case Plane.PlaneIntersectionType_Intersecting:
  12175. return ContainmentType.Intersects;
  12176. default:
  12177. return ContainmentType.Contains;
  12178. }
  12179. }
  12180. intersects(box) {
  12181. var min = box.min;
  12182. var max = box.max;
  12183. var minX = min.x;
  12184. var minY = min.y;
  12185. var minZ = min.z;
  12186. var maxX = max.x;
  12187. var maxY = max.y;
  12188. var maxZ = max.z;
  12189. var nearNormal = this._near.normal;
  12190. 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)
  12191. return false;
  12192. var leftNormal = this._left.normal;
  12193. 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)
  12194. return false;
  12195. var rightNormal = this._right.normal;
  12196. 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)
  12197. return false;
  12198. var bottomNormal = this._bottom.normal;
  12199. 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)
  12200. return false;
  12201. var topNormal = this._top.normal;
  12202. 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)
  12203. return false;
  12204. var farNormal = this._far.normal;
  12205. 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)
  12206. return false;
  12207. return true;
  12208. }
  12209. containsBoundBox(box) {
  12210. var p = BoundFrustum._tempV30, n = BoundFrustum._tempV31;
  12211. var boxMin = box.min;
  12212. var boxMax = box.max;
  12213. var result = ContainmentType.Contains;
  12214. for (var i = 0; i < 6; i++) {
  12215. var plane = this.getPlane(i);
  12216. var planeNor = plane.normal;
  12217. if (planeNor.x >= 0) {
  12218. p.x = boxMax.x;
  12219. n.x = boxMin.x;
  12220. }
  12221. else {
  12222. p.x = boxMin.x;
  12223. n.x = boxMax.x;
  12224. }
  12225. if (planeNor.y >= 0) {
  12226. p.y = boxMax.y;
  12227. n.y = boxMin.y;
  12228. }
  12229. else {
  12230. p.y = boxMin.y;
  12231. n.y = boxMax.y;
  12232. }
  12233. if (planeNor.z >= 0) {
  12234. p.z = boxMax.z;
  12235. n.z = boxMin.z;
  12236. }
  12237. else {
  12238. p.z = boxMin.z;
  12239. n.z = boxMax.z;
  12240. }
  12241. if (CollisionUtils.intersectsPlaneAndPoint(plane, p) === Plane.PlaneIntersectionType_Back)
  12242. return ContainmentType.Disjoint;
  12243. if (CollisionUtils.intersectsPlaneAndPoint(plane, n) === Plane.PlaneIntersectionType_Back)
  12244. result = ContainmentType.Intersects;
  12245. }
  12246. return result;
  12247. }
  12248. containsBoundSphere(sphere) {
  12249. var result = Plane.PlaneIntersectionType_Front;
  12250. var planeResult = Plane.PlaneIntersectionType_Front;
  12251. for (var i = 0; i < 6; i++) {
  12252. switch (i) {
  12253. case 0:
  12254. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._near, sphere);
  12255. break;
  12256. case 1:
  12257. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._far, sphere);
  12258. break;
  12259. case 2:
  12260. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._left, sphere);
  12261. break;
  12262. case 3:
  12263. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._right, sphere);
  12264. break;
  12265. case 4:
  12266. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._top, sphere);
  12267. break;
  12268. case 5:
  12269. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._bottom, sphere);
  12270. break;
  12271. }
  12272. switch (planeResult) {
  12273. case Plane.PlaneIntersectionType_Back:
  12274. return ContainmentType.Disjoint;
  12275. case Plane.PlaneIntersectionType_Intersecting:
  12276. result = Plane.PlaneIntersectionType_Intersecting;
  12277. break;
  12278. }
  12279. }
  12280. switch (result) {
  12281. case Plane.PlaneIntersectionType_Intersecting:
  12282. return ContainmentType.Intersects;
  12283. default:
  12284. return ContainmentType.Contains;
  12285. }
  12286. }
  12287. }
  12288. BoundFrustum._tempV30 = new Vector3();
  12289. BoundFrustum._tempV31 = new Vector3();
  12290. BoundFrustum._tempV32 = new Vector3();
  12291. BoundFrustum._tempV33 = new Vector3();
  12292. BoundFrustum._tempV34 = new Vector3();
  12293. BoundFrustum._tempV35 = new Vector3();
  12294. BoundFrustum._tempV36 = new Vector3();
  12295. BoundFrustum._tempV37 = new Vector3();
  12296. class Viewport {
  12297. constructor(x, y, width, height) {
  12298. this.minDepth = 0.0;
  12299. this.maxDepth = 1.0;
  12300. this.x = x;
  12301. this.y = y;
  12302. this.width = width;
  12303. this.height = height;
  12304. }
  12305. project(source, matrix, out) {
  12306. var sX = source.x;
  12307. var sY = source.y;
  12308. var sZ = source.z;
  12309. Vector3.transformV3ToV3(source, matrix, out);
  12310. var matE = matrix.elements;
  12311. var a = (((sX * matE[3]) + (sY * matE[7])) + (sZ * matE[11])) + matE[15];
  12312. if (a !== 1.0) {
  12313. out.x = out.x / a;
  12314. out.y = out.y / a;
  12315. out.z = out.z / a;
  12316. }
  12317. out.x = (((out.x + 1.0) * 0.5) * this.width) + this.x;
  12318. out.y = (((-out.y + 1.0) * 0.5) * this.height) + this.y;
  12319. out.z = (out.z * (this.maxDepth - this.minDepth)) + this.minDepth;
  12320. }
  12321. unprojectFromMat(source, matrix, out) {
  12322. var matrixEleme = matrix.elements;
  12323. out.x = (((source.x - this.x) / (this.width)) * 2.0) - 1.0;
  12324. out.y = -((((source.y - this.y) / (this.height)) * 2.0) - 1.0);
  12325. var halfDepth = (this.maxDepth - this.minDepth) / 2;
  12326. out.z = (source.z - this.minDepth - halfDepth) / halfDepth;
  12327. var a = (((out.x * matrixEleme[3]) + (out.y * matrixEleme[7])) + (out.z * matrixEleme[11])) + matrixEleme[15];
  12328. Vector3.transformV3ToV3(out, matrix, out);
  12329. if (a !== 1.0) {
  12330. out.x = out.x / a;
  12331. out.y = out.y / a;
  12332. out.z = out.z / a;
  12333. }
  12334. }
  12335. unprojectFromWVP(source, projection, view, world, out) {
  12336. Matrix4x4.multiply(projection, view, Viewport._tempMatrix4x4);
  12337. (world) && (Matrix4x4.multiply(Viewport._tempMatrix4x4, world, Viewport._tempMatrix4x4));
  12338. Viewport._tempMatrix4x4.invert(Viewport._tempMatrix4x4);
  12339. this.unprojectFromMat(source, Viewport._tempMatrix4x4, out);
  12340. }
  12341. cloneTo(out) {
  12342. out.x = this.x;
  12343. out.y = this.y;
  12344. out.width = this.width;
  12345. out.height = this.height;
  12346. out.minDepth = this.minDepth;
  12347. out.maxDepth = this.maxDepth;
  12348. }
  12349. }
  12350. Viewport._tempMatrix4x4 = new Matrix4x4();
  12351. class Picker {
  12352. constructor() {
  12353. }
  12354. static calculateCursorRay(point, viewPort, projectionMatrix, viewMatrix, world, out) {
  12355. var x = point.x;
  12356. var y = point.y;
  12357. var nearSource = Picker._tempVector30;
  12358. var nerSourceE = nearSource;
  12359. nerSourceE.x = x;
  12360. nerSourceE.y = y;
  12361. nerSourceE.z = viewPort.minDepth;
  12362. var farSource = Picker._tempVector31;
  12363. var farSourceE = farSource;
  12364. farSourceE.x = x;
  12365. farSourceE.y = y;
  12366. farSourceE.z = viewPort.maxDepth;
  12367. var nearPoint = out.origin;
  12368. var farPoint = Picker._tempVector32;
  12369. viewPort.unprojectFromWVP(nearSource, projectionMatrix, viewMatrix, world, nearPoint);
  12370. viewPort.unprojectFromWVP(farSource, projectionMatrix, viewMatrix, world, farPoint);
  12371. var outDire = out.direction;
  12372. outDire.x = farPoint.x - nearPoint.x;
  12373. outDire.y = farPoint.y - nearPoint.y;
  12374. outDire.z = farPoint.z - nearPoint.z;
  12375. Vector3.normalize(out.direction, out.direction);
  12376. }
  12377. static rayIntersectsTriangle(ray, vertex1, vertex2, vertex3) {
  12378. var result;
  12379. var edge1 = Picker._tempVector30, edge2 = Picker._tempVector31;
  12380. Vector3.subtract(vertex2, vertex1, edge1);
  12381. Vector3.subtract(vertex3, vertex1, edge2);
  12382. var directionCrossEdge2 = Picker._tempVector32;
  12383. Vector3.cross(ray.direction, edge2, directionCrossEdge2);
  12384. var determinant;
  12385. determinant = Vector3.dot(edge1, directionCrossEdge2);
  12386. if (determinant > -Number.MIN_VALUE && determinant < Number.MIN_VALUE) {
  12387. result = Number.NaN;
  12388. return result;
  12389. }
  12390. var inverseDeterminant = 1.0 / determinant;
  12391. var distanceVector = Picker._tempVector33;
  12392. Vector3.subtract(ray.origin, vertex1, distanceVector);
  12393. var triangleU;
  12394. triangleU = Vector3.dot(distanceVector, directionCrossEdge2);
  12395. triangleU *= inverseDeterminant;
  12396. if (triangleU < 0 || triangleU > 1) {
  12397. result = Number.NaN;
  12398. return result;
  12399. }
  12400. var distanceCrossEdge1 = Picker._tempVector34;
  12401. Vector3.cross(distanceVector, edge1, distanceCrossEdge1);
  12402. var triangleV;
  12403. triangleV = Vector3.dot(ray.direction, distanceCrossEdge1);
  12404. triangleV *= inverseDeterminant;
  12405. if (triangleV < 0 || triangleU + triangleV > 1) {
  12406. result = Number.NaN;
  12407. return result;
  12408. }
  12409. var rayDistance;
  12410. rayDistance = Vector3.dot(edge2, distanceCrossEdge1);
  12411. rayDistance *= inverseDeterminant;
  12412. if (rayDistance < 0) {
  12413. result = Number.NaN;
  12414. return result;
  12415. }
  12416. result = rayDistance;
  12417. return result;
  12418. }
  12419. }
  12420. Picker._tempVector30 = new Vector3();
  12421. Picker._tempVector31 = new Vector3();
  12422. Picker._tempVector32 = new Vector3();
  12423. Picker._tempVector33 = new Vector3();
  12424. Picker._tempVector34 = new Vector3();
  12425. class SystemUtils {
  12426. static supportTextureFormat(format) {
  12427. switch (format) {
  12428. case Laya.TextureFormat.R32G32B32A32:
  12429. if (!Laya.LayaGL.layaGPUInstance._isWebGL2 && !Laya.LayaGL.layaGPUInstance._oesTextureFloat)
  12430. return false;
  12431. else
  12432. return true;
  12433. default:
  12434. return true;
  12435. }
  12436. }
  12437. static supportRenderTextureFormat(format) {
  12438. switch (format) {
  12439. case Laya.RenderTextureFormat.R16G16B16A16:
  12440. if (Laya.LayaGL.layaGPUInstance._isWebGL2 || Laya.LayaGL.layaGPUInstance._oesTextureHalfFloat && Laya.LayaGL.layaGPUInstance._oesTextureHalfFloatLinear)
  12441. return true;
  12442. else
  12443. return false;
  12444. default:
  12445. return true;
  12446. }
  12447. }
  12448. }
  12449. class BufferState extends Laya.BufferStateBase {
  12450. constructor() {
  12451. super();
  12452. }
  12453. applyVertexBuffer(vertexBuffer) {
  12454. if (Laya.BufferStateBase._curBindedBufferState === this) {
  12455. var gl = Laya.LayaGL.instance;
  12456. var verDec = vertexBuffer.vertexDeclaration;
  12457. var valueData = verDec._shaderValues.getData();
  12458. this.vertexDeclaration = verDec;
  12459. vertexBuffer.bind();
  12460. for (var k in valueData) {
  12461. var loc = parseInt(k);
  12462. var attribute = valueData[k];
  12463. gl.enableVertexAttribArray(loc);
  12464. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  12465. }
  12466. }
  12467. else {
  12468. throw "BufferState: must call bind() function first.";
  12469. }
  12470. }
  12471. applyVertexBuffers(vertexBuffers) {
  12472. if (Laya.BufferStateBase._curBindedBufferState === this) {
  12473. var gl = Laya.LayaGL.instance;
  12474. for (var i = 0, n = vertexBuffers.length; i < n; i++) {
  12475. var verBuf = vertexBuffers[i];
  12476. var verDec = verBuf.vertexDeclaration;
  12477. var valueData = verDec._shaderValues.getData();
  12478. verBuf.bind();
  12479. for (var k in valueData) {
  12480. var loc = parseInt(k);
  12481. var attribute = valueData[k];
  12482. gl.enableVertexAttribArray(loc);
  12483. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  12484. }
  12485. }
  12486. }
  12487. else {
  12488. throw "BufferState: must call bind() function first.";
  12489. }
  12490. }
  12491. applyInstanceVertexBuffer(vertexBuffer) {
  12492. if (Laya.LayaGL.layaGPUInstance.supportInstance()) {
  12493. if (Laya.BufferStateBase._curBindedBufferState === this) {
  12494. var gl = Laya.LayaGL.instance;
  12495. var verDec = vertexBuffer.vertexDeclaration;
  12496. var valueData = verDec._shaderValues.getData();
  12497. vertexBuffer.bind();
  12498. for (var k in valueData) {
  12499. var loc = parseInt(k);
  12500. var attribute = valueData[k];
  12501. gl.enableVertexAttribArray(loc);
  12502. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  12503. Laya.LayaGL.layaGPUInstance.vertexAttribDivisor(loc, 1);
  12504. }
  12505. }
  12506. else {
  12507. throw "BufferState: must call bind() function first.";
  12508. }
  12509. }
  12510. }
  12511. applyIndexBuffer(indexBuffer) {
  12512. if (Laya.BufferStateBase._curBindedBufferState === this) {
  12513. if (this._bindedIndexBuffer !== indexBuffer) {
  12514. indexBuffer._bindForVAO();
  12515. this._bindedIndexBuffer = indexBuffer;
  12516. }
  12517. }
  12518. else {
  12519. throw "BufferState: must call bind() function first.";
  12520. }
  12521. }
  12522. }
  12523. class IndexBuffer3D extends Laya.Buffer {
  12524. constructor(indexType, indexCount, bufferUsage = 0x88E4, canRead = false) {
  12525. super();
  12526. this._indexType = indexType;
  12527. this._indexCount = indexCount;
  12528. this._bufferUsage = bufferUsage;
  12529. this._bufferType = Laya.LayaGL.instance.ELEMENT_ARRAY_BUFFER;
  12530. this._canRead = canRead;
  12531. var byteLength;
  12532. if (indexType == IndexBuffer3D.INDEXTYPE_USHORT)
  12533. this._indexTypeByteCount = 2;
  12534. else if (indexType == IndexBuffer3D.INDEXTYPE_UBYTE)
  12535. this._indexTypeByteCount = 1;
  12536. else
  12537. throw new Error("unidentification index type.");
  12538. byteLength = this._indexTypeByteCount * indexCount;
  12539. this._byteLength = byteLength;
  12540. var curBufSta = Laya.BufferStateBase._curBindedBufferState;
  12541. if (curBufSta) {
  12542. if (curBufSta._bindedIndexBuffer === this) {
  12543. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  12544. }
  12545. else {
  12546. curBufSta.unBind();
  12547. this.bind();
  12548. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  12549. curBufSta.bind();
  12550. }
  12551. }
  12552. else {
  12553. this.bind();
  12554. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  12555. }
  12556. if (canRead) {
  12557. if (indexType == IndexBuffer3D.INDEXTYPE_USHORT)
  12558. this._buffer = new Uint16Array(indexCount);
  12559. else if (indexType == IndexBuffer3D.INDEXTYPE_UBYTE)
  12560. this._buffer = new Uint8Array(indexCount);
  12561. }
  12562. }
  12563. get indexType() {
  12564. return this._indexType;
  12565. }
  12566. get indexTypeByteCount() {
  12567. return this._indexTypeByteCount;
  12568. }
  12569. get indexCount() {
  12570. return this._indexCount;
  12571. }
  12572. get canRead() {
  12573. return this._canRead;
  12574. }
  12575. _bindForVAO() {
  12576. if (Laya.BufferStateBase._curBindedBufferState) {
  12577. var gl = Laya.LayaGL.instance;
  12578. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glBuffer);
  12579. }
  12580. else {
  12581. throw "IndexBuffer3D: must bind current BufferState.";
  12582. }
  12583. }
  12584. bind() {
  12585. if (Laya.BufferStateBase._curBindedBufferState) {
  12586. throw "IndexBuffer3D: must unbind current BufferState.";
  12587. }
  12588. else {
  12589. if (Laya.Buffer._bindedIndexBuffer !== this._glBuffer) {
  12590. var gl = Laya.LayaGL.instance;
  12591. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glBuffer);
  12592. Laya.Buffer._bindedIndexBuffer = this._glBuffer;
  12593. return true;
  12594. }
  12595. else {
  12596. return false;
  12597. }
  12598. }
  12599. }
  12600. setData(data, bufferOffset = 0, dataStartIndex = 0, dataCount = 4294967295) {
  12601. var byteCount;
  12602. if (this._indexType == IndexBuffer3D.INDEXTYPE_USHORT) {
  12603. byteCount = 2;
  12604. if (dataStartIndex !== 0 || dataCount !== 4294967295)
  12605. data = new Uint16Array(data.buffer, dataStartIndex * byteCount, dataCount);
  12606. }
  12607. else if (this._indexType == IndexBuffer3D.INDEXTYPE_UBYTE) {
  12608. byteCount = 1;
  12609. if (dataStartIndex !== 0 || dataCount !== 4294967295)
  12610. data = new Uint8Array(data.buffer, dataStartIndex * byteCount, dataCount);
  12611. }
  12612. var curBufSta = Laya.BufferStateBase._curBindedBufferState;
  12613. if (curBufSta) {
  12614. if (curBufSta._bindedIndexBuffer === this) {
  12615. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  12616. }
  12617. else {
  12618. curBufSta.unBind();
  12619. this.bind();
  12620. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  12621. curBufSta.bind();
  12622. }
  12623. }
  12624. else {
  12625. this.bind();
  12626. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  12627. }
  12628. if (this._canRead) {
  12629. if (bufferOffset !== 0 || dataStartIndex !== 0 || dataCount !== 4294967295) {
  12630. var maxLength = this._buffer.length - bufferOffset;
  12631. if (dataCount > maxLength)
  12632. dataCount = maxLength;
  12633. for (var i = 0; i < dataCount; i++)
  12634. this._buffer[bufferOffset + i] = data[i];
  12635. }
  12636. else {
  12637. this._buffer = data;
  12638. }
  12639. }
  12640. }
  12641. getData() {
  12642. if (this._canRead)
  12643. return this._buffer;
  12644. else
  12645. throw new Error("Can't read data from VertexBuffer with only write flag!");
  12646. }
  12647. destroy() {
  12648. super.destroy();
  12649. this._buffer = null;
  12650. }
  12651. }
  12652. IndexBuffer3D.INDEXTYPE_UBYTE = "ubyte";
  12653. IndexBuffer3D.INDEXTYPE_USHORT = "ushort";
  12654. class SkyMesh {
  12655. constructor() {
  12656. }
  12657. _render(state) {
  12658. }
  12659. }
  12660. class SkyBox extends SkyMesh {
  12661. static __init__() {
  12662. SkyBox.instance = new SkyBox();
  12663. }
  12664. constructor() {
  12665. super();
  12666. var gl = Laya.LayaGL.instance;
  12667. var halfHeight = 1.0;
  12668. var halfWidth = 1.0;
  12669. var halfDepth = 1.0;
  12670. var vertices = new Float32Array([-halfDepth, halfHeight, -halfWidth, halfDepth, halfHeight, -halfWidth, halfDepth, halfHeight, halfWidth, -halfDepth, halfHeight, halfWidth,
  12671. -halfDepth, -halfHeight, -halfWidth, halfDepth, -halfHeight, -halfWidth, halfDepth, -halfHeight, halfWidth, -halfDepth, -halfHeight, halfWidth]);
  12672. var indices = new Uint8Array([
  12673. 0, 1, 2, 2, 3, 0,
  12674. 4, 7, 6, 6, 5, 4,
  12675. 0, 3, 7, 7, 4, 0,
  12676. 1, 5, 6, 6, 2, 1,
  12677. 3, 2, 6, 6, 7, 3,
  12678. 0, 4, 5, 5, 1, 0
  12679. ]);
  12680. var verDec = VertexMesh.getVertexDeclaration("POSITION");
  12681. this._vertexBuffer = new VertexBuffer3D(verDec.vertexStride * 8, gl.STATIC_DRAW, false);
  12682. this._vertexBuffer.vertexDeclaration = verDec;
  12683. this._indexBuffer = new IndexBuffer3D(IndexBuffer3D.INDEXTYPE_UBYTE, 36, gl.STATIC_DRAW, false);
  12684. this._vertexBuffer.setData(vertices.buffer);
  12685. this._indexBuffer.setData(indices);
  12686. var bufferState = new BufferState();
  12687. bufferState.bind();
  12688. bufferState.applyVertexBuffer(this._vertexBuffer);
  12689. bufferState.applyIndexBuffer(this._indexBuffer);
  12690. bufferState.unBind();
  12691. this._bufferState = bufferState;
  12692. }
  12693. _render(state) {
  12694. var gl = Laya.LayaGL.instance;
  12695. gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_BYTE, 0);
  12696. Laya.Stat.trianglesFaces += 12;
  12697. Laya.Stat.renderBatches++;
  12698. }
  12699. }
  12700. class SkyRenderer {
  12701. constructor() {
  12702. this._mesh = SkyBox.instance;
  12703. }
  12704. get material() {
  12705. return this._material;
  12706. }
  12707. set material(value) {
  12708. if (this._material !== value) {
  12709. (this._material) && (this._material._removeReference());
  12710. (value) && (value._addReference());
  12711. this._material = value;
  12712. }
  12713. }
  12714. get mesh() {
  12715. return this._mesh;
  12716. }
  12717. set mesh(value) {
  12718. if (this._mesh !== value) {
  12719. this._mesh = value;
  12720. }
  12721. }
  12722. _isAvailable() {
  12723. return this._material && this._mesh ? true : false;
  12724. }
  12725. _render(state) {
  12726. if (this._material && this._mesh) {
  12727. var gl = Laya.LayaGL.instance;
  12728. var scene = state.scene;
  12729. var camera = state.camera;
  12730. var noteValue = ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_;
  12731. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(false);
  12732. Laya.WebGLContext.setCullFace(gl, false);
  12733. Laya.WebGLContext.setDepthFunc(gl, gl.LEQUAL);
  12734. Laya.WebGLContext.setDepthMask(gl, false);
  12735. var comDef = SkyRenderer._compileDefine;
  12736. this._material._shaderValues._defineDatas.cloneTo(comDef);
  12737. var shader = state.shader = this._material._shader.getSubShaderAt(0)._passes[0].withCompile(comDef);
  12738. var switchShader = shader.bind();
  12739. var switchShaderLoop = (Laya.Stat.loopCount !== shader._uploadMark);
  12740. var uploadScene = (shader._uploadScene !== scene) || switchShaderLoop;
  12741. if (uploadScene || switchShader) {
  12742. shader.uploadUniforms(shader._sceneUniformParamsMap, scene._shaderValues, uploadScene);
  12743. shader._uploadScene = scene;
  12744. }
  12745. var renderTar = camera._getInternalRenderTexture();
  12746. var uploadCamera = (shader._uploadCamera !== camera) || switchShaderLoop;
  12747. if (uploadCamera || switchShader) {
  12748. var viewMatrix = SkyRenderer._tempMatrix0;
  12749. var projectionMatrix = SkyRenderer._tempMatrix1;
  12750. camera.viewMatrix.cloneTo(viewMatrix);
  12751. camera.projectionMatrix.cloneTo(projectionMatrix);
  12752. viewMatrix.setTranslationVector(Vector3._ZERO);
  12753. if (camera.orthographic)
  12754. Matrix4x4.createPerspective(camera.fieldOfView, camera.aspectRatio, camera.nearPlane, camera.farPlane, projectionMatrix);
  12755. var epsilon = 1e-6;
  12756. var yScale = 1.0 / Math.tan(3.1416 * camera.fieldOfView / 180 * 0.5);
  12757. projectionMatrix.elements[0] = yScale / camera.aspectRatio;
  12758. projectionMatrix.elements[5] = yScale;
  12759. projectionMatrix.elements[10] = epsilon - 1.0;
  12760. projectionMatrix.elements[11] = -1.0;
  12761. projectionMatrix.elements[14] = -0;
  12762. camera._applyViewProject(state, viewMatrix, projectionMatrix, renderTar ? true : false);
  12763. shader.uploadUniforms(shader._cameraUniformParamsMap, camera._shaderValues, uploadCamera);
  12764. shader._uploadCamera = camera;
  12765. }
  12766. var uploadMaterial = (shader._uploadMaterial !== this._material) || switchShaderLoop;
  12767. if (uploadMaterial || switchShader) {
  12768. shader.uploadUniforms(shader._materialUniformParamsMap, this._material._shaderValues, uploadMaterial);
  12769. shader._uploadMaterial = this._material;
  12770. }
  12771. this._mesh._bufferState.bind();
  12772. this._mesh._render(state);
  12773. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(noteValue);
  12774. Laya.WebGLContext.setDepthFunc(gl, gl.LESS);
  12775. Laya.WebGLContext.setDepthMask(gl, true);
  12776. camera._applyViewProject(state, camera.viewMatrix, camera.projectionMatrix, renderTar ? true : false);
  12777. }
  12778. }
  12779. destroy() {
  12780. if (this._material) {
  12781. this._material._removeReference();
  12782. this._material = null;
  12783. }
  12784. }
  12785. }
  12786. SkyRenderer._tempMatrix0 = new Matrix4x4();
  12787. SkyRenderer._tempMatrix1 = new Matrix4x4();
  12788. SkyRenderer._compileDefine = new DefineDatas();
  12789. class BaseCamera extends Sprite3D {
  12790. constructor(nearPlane = 0.3, farPlane = 1000) {
  12791. super();
  12792. this._skyRenderer = new SkyRenderer();
  12793. this._forward = new Vector3();
  12794. this._up = new Vector3();
  12795. this.clearColor = new Vector4(100 / 255, 149 / 255, 237 / 255, 255 / 255);
  12796. this._shaderValues = new ShaderData(null);
  12797. this._fieldOfView = 60;
  12798. this._useUserProjectionMatrix = false;
  12799. this._orthographic = false;
  12800. this._orthographicVerticalSize = 10;
  12801. this.renderingOrder = 0;
  12802. this._nearPlane = nearPlane;
  12803. this._farPlane = farPlane;
  12804. this.cullingMask = 2147483647;
  12805. this.clearFlag = BaseCamera.CLEARFLAG_SOLIDCOLOR;
  12806. this.useOcclusionCulling = true;
  12807. }
  12808. get skyRenderer() {
  12809. return this._skyRenderer;
  12810. }
  12811. get fieldOfView() {
  12812. return this._fieldOfView;
  12813. }
  12814. set fieldOfView(value) {
  12815. this._fieldOfView = value;
  12816. this._calculateProjectionMatrix();
  12817. }
  12818. get nearPlane() {
  12819. return this._nearPlane;
  12820. }
  12821. set nearPlane(value) {
  12822. this._nearPlane = value;
  12823. this._calculateProjectionMatrix();
  12824. }
  12825. get farPlane() {
  12826. return this._farPlane;
  12827. }
  12828. set farPlane(vaule) {
  12829. this._farPlane = vaule;
  12830. this._calculateProjectionMatrix();
  12831. }
  12832. get orthographic() {
  12833. return this._orthographic;
  12834. }
  12835. set orthographic(vaule) {
  12836. this._orthographic = vaule;
  12837. this._calculateProjectionMatrix();
  12838. }
  12839. get orthographicVerticalSize() {
  12840. return this._orthographicVerticalSize;
  12841. }
  12842. set orthographicVerticalSize(vaule) {
  12843. this._orthographicVerticalSize = vaule;
  12844. this._calculateProjectionMatrix();
  12845. }
  12846. get renderingOrder() {
  12847. return this._renderingOrder;
  12848. }
  12849. set renderingOrder(value) {
  12850. this._renderingOrder = value;
  12851. this._sortCamerasByRenderingOrder();
  12852. }
  12853. _sortCamerasByRenderingOrder() {
  12854. if (this.displayedInStage) {
  12855. var cameraPool = this.scene._cameraPool;
  12856. var n = cameraPool.length - 1;
  12857. for (var i = 0; i < n; i++) {
  12858. if (cameraPool[i].renderingOrder > cameraPool[n].renderingOrder) {
  12859. var tempCamera = cameraPool[i];
  12860. cameraPool[i] = cameraPool[n];
  12861. cameraPool[n] = tempCamera;
  12862. }
  12863. }
  12864. }
  12865. }
  12866. _calculateProjectionMatrix() {
  12867. }
  12868. _onScreenSizeChanged() {
  12869. this._calculateProjectionMatrix();
  12870. }
  12871. _prepareCameraToRender() {
  12872. var cameraSV = this._shaderValues;
  12873. this.transform.getForward(this._forward);
  12874. this.transform.getUp(this._up);
  12875. cameraSV.setVector3(BaseCamera.CAMERAPOS, this.transform.position);
  12876. cameraSV.setVector3(BaseCamera.CAMERADIRECTION, this._forward);
  12877. cameraSV.setVector3(BaseCamera.CAMERAUP, this._up);
  12878. }
  12879. render(shader = null, replacementTag = null) {
  12880. }
  12881. addLayer(layer) {
  12882. this.cullingMask |= Math.pow(2, layer);
  12883. }
  12884. removeLayer(layer) {
  12885. this.cullingMask &= ~Math.pow(2, layer);
  12886. }
  12887. addAllLayers() {
  12888. this.cullingMask = 2147483647;
  12889. }
  12890. removeAllLayers() {
  12891. this.cullingMask = 0;
  12892. }
  12893. resetProjectionMatrix() {
  12894. this._useUserProjectionMatrix = false;
  12895. this._calculateProjectionMatrix();
  12896. }
  12897. _onActive() {
  12898. this._scene._addCamera(this);
  12899. super._onActive();
  12900. }
  12901. _onInActive() {
  12902. this._scene._removeCamera(this);
  12903. super._onInActive();
  12904. }
  12905. _parse(data, spriteMap) {
  12906. super._parse(data, spriteMap);
  12907. var clearFlagData = data.clearFlag;
  12908. (clearFlagData !== undefined) && (this.clearFlag = clearFlagData);
  12909. this.orthographic = data.orthographic;
  12910. (data.orthographicVerticalSize !== undefined) && (this.orthographicVerticalSize = data.orthographicVerticalSize);
  12911. (data.fieldOfView !== undefined) && (this.fieldOfView = data.fieldOfView);
  12912. this.nearPlane = data.nearPlane;
  12913. this.farPlane = data.farPlane;
  12914. var color = data.clearColor;
  12915. this.clearColor = new Vector4(color[0], color[1], color[2], color[3]);
  12916. var skyboxMaterial = data.skyboxMaterial;
  12917. if (skyboxMaterial) {
  12918. this._skyRenderer.material = Laya.Loader.getRes(skyboxMaterial.path);
  12919. }
  12920. }
  12921. destroy(destroyChild = true) {
  12922. this._skyRenderer.destroy();
  12923. this._skyRenderer = null;
  12924. Laya.Laya.stage.off(Laya.Event.RESIZE, this, this._onScreenSizeChanged);
  12925. super.destroy(destroyChild);
  12926. }
  12927. _create() {
  12928. return new BaseCamera();
  12929. }
  12930. }
  12931. BaseCamera._tempMatrix4x40 = new Matrix4x4();
  12932. BaseCamera.CAMERAPOS = Shader3D.propertyNameToID("u_CameraPos");
  12933. BaseCamera.VIEWMATRIX = Shader3D.propertyNameToID("u_View");
  12934. BaseCamera.PROJECTMATRIX = Shader3D.propertyNameToID("u_Projection");
  12935. BaseCamera.VIEWPROJECTMATRIX = Shader3D.propertyNameToID("u_ViewProjection");
  12936. BaseCamera.CAMERADIRECTION = Shader3D.propertyNameToID("u_CameraDirection");
  12937. BaseCamera.CAMERAUP = Shader3D.propertyNameToID("u_CameraUp");
  12938. BaseCamera.VIEWPORT = Shader3D.propertyNameToID("u_Viewport");
  12939. BaseCamera.PROJECTION_PARAMS = Shader3D.propertyNameToID("u_ProjectionParams");
  12940. BaseCamera.RENDERINGTYPE_DEFERREDLIGHTING = "DEFERREDLIGHTING";
  12941. BaseCamera.RENDERINGTYPE_FORWARDRENDERING = "FORWARDRENDERING";
  12942. BaseCamera.CLEARFLAG_SOLIDCOLOR = 0;
  12943. BaseCamera.CLEARFLAG_SKY = 1;
  12944. BaseCamera.CLEARFLAG_DEPTHONLY = 2;
  12945. BaseCamera.CLEARFLAG_NONE = 3;
  12946. BaseCamera._invertYScaleMatrix = new Matrix4x4(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  12947. BaseCamera._invertYProjectionMatrix = new Matrix4x4();
  12948. BaseCamera._invertYProjectionViewMatrix = new Matrix4x4();
  12949. class ScreenQuad extends Laya.Resource {
  12950. constructor() {
  12951. super();
  12952. this._bufferState = new BufferState();
  12953. this._bufferStateInvertUV = new BufferState();
  12954. var gl = Laya.LayaGL.instance;
  12955. this._vertexBuffer = new VertexBuffer3D(16 * 4, gl.STATIC_DRAW, false);
  12956. this._vertexBuffer.vertexDeclaration = ScreenQuad._vertexDeclaration;
  12957. this._vertexBuffer.setData(ScreenQuad._vertices.buffer);
  12958. this._bufferState.bind();
  12959. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  12960. this._bufferState.unBind();
  12961. this._vertexBufferInvertUV = new VertexBuffer3D(16 * 4, gl.STATIC_DRAW, false);
  12962. this._vertexBufferInvertUV.vertexDeclaration = ScreenQuad._vertexDeclaration;
  12963. this._vertexBufferInvertUV.setData(ScreenQuad._verticesInvertUV.buffer);
  12964. this._bufferStateInvertUV.bind();
  12965. this._bufferStateInvertUV.applyVertexBuffer(this._vertexBufferInvertUV);
  12966. this._bufferStateInvertUV.unBind();
  12967. this._setGPUMemory(this._vertexBuffer._byteLength + this._vertexBufferInvertUV._byteLength);
  12968. }
  12969. static __init__() {
  12970. ScreenQuad._vertexDeclaration = new VertexDeclaration(16, [new VertexElement(0, VertexElementFormat.Vector4, ScreenQuad.SCREENQUAD_POSITION_UV)]);
  12971. ScreenQuad.instance = new ScreenQuad();
  12972. ScreenQuad.instance.lock = true;
  12973. }
  12974. render() {
  12975. var gl = Laya.LayaGL.instance;
  12976. this._bufferState.bind();
  12977. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  12978. Laya.Stat.renderBatches++;
  12979. }
  12980. renderInvertUV() {
  12981. var gl = Laya.LayaGL.instance;
  12982. this._bufferStateInvertUV.bind();
  12983. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  12984. Laya.Stat.renderBatches++;
  12985. }
  12986. destroy() {
  12987. super.destroy();
  12988. this._bufferState.destroy();
  12989. this._vertexBuffer.destroy();
  12990. this._bufferStateInvertUV.destroy();
  12991. this._vertexBufferInvertUV.destroy();
  12992. this._setGPUMemory(0);
  12993. }
  12994. }
  12995. ScreenQuad.SCREENQUAD_POSITION_UV = 0;
  12996. ScreenQuad._vertices = new Float32Array([1, 1, 1, 0, 1, -1, 1, 1, -1, 1, 0, 0, -1, -1, 0, 1]);
  12997. ScreenQuad._verticesInvertUV = new Float32Array([1, 1, 1, 1, 1, -1, 1, 0, -1, 1, 0, 1, -1, -1, 0, 0]);
  12998. class ScreenTriangle extends Laya.Resource {
  12999. constructor() {
  13000. super();
  13001. this._bufferState = new BufferState();
  13002. this._bufferStateInvertUV = new BufferState();
  13003. var gl = Laya.LayaGL.instance;
  13004. this._vertexBuffer = new VertexBuffer3D(12 * 4, gl.STATIC_DRAW, false);
  13005. this._vertexBuffer.vertexDeclaration = ScreenTriangle._vertexDeclaration;
  13006. this._vertexBuffer.setData(ScreenTriangle._vertices.buffer);
  13007. this._bufferState.bind();
  13008. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  13009. this._bufferState.unBind();
  13010. this._vertexBufferInvertUV = new VertexBuffer3D(12 * 4, gl.STATIC_DRAW, false);
  13011. this._vertexBufferInvertUV.vertexDeclaration = ScreenTriangle._vertexDeclaration;
  13012. this._vertexBufferInvertUV.setData(ScreenTriangle._verticesInvertUV.buffer);
  13013. this._bufferStateInvertUV.bind();
  13014. this._bufferStateInvertUV.applyVertexBuffer(this._vertexBufferInvertUV);
  13015. this._bufferStateInvertUV.unBind();
  13016. this._setGPUMemory(this._vertexBuffer._byteLength + this._vertexBufferInvertUV._byteLength);
  13017. }
  13018. static __init__() {
  13019. ScreenTriangle._vertexDeclaration = new VertexDeclaration(16, [new VertexElement(0, VertexElementFormat.Vector4, ScreenTriangle.SCREENTRIANGLE_POSITION_UV)]);
  13020. ScreenTriangle.instance = new ScreenTriangle();
  13021. ScreenTriangle.instance.lock = true;
  13022. }
  13023. render() {
  13024. var gl = Laya.LayaGL.instance;
  13025. this._bufferState.bind();
  13026. gl.drawArrays(gl.TRIANGLES, 0, 3);
  13027. Laya.Stat.renderBatches++;
  13028. }
  13029. renderInvertUV() {
  13030. var gl = Laya.LayaGL.instance;
  13031. this._bufferStateInvertUV.bind();
  13032. gl.drawArrays(gl.TRIANGLES, 0, 3);
  13033. Laya.Stat.renderBatches++;
  13034. }
  13035. destroy() {
  13036. super.destroy();
  13037. this._bufferState.destroy();
  13038. this._vertexBuffer.destroy();
  13039. this._bufferStateInvertUV.destroy();
  13040. this._vertexBufferInvertUV.destroy();
  13041. this._setGPUMemory(0);
  13042. }
  13043. }
  13044. ScreenTriangle.SCREENTRIANGLE_POSITION_UV = 0;
  13045. ScreenTriangle._vertices = new Float32Array([-1, -1, 0, 1, -1, 3, 0, -1, 3, -1, 2, 1]);
  13046. ScreenTriangle._verticesInvertUV = new Float32Array([-1, -1, 0, 0, -1, 3, 0, 2, 3, -1, 2, 0]);
  13047. class Command {
  13048. constructor() {
  13049. this._commandBuffer = null;
  13050. }
  13051. static __init__() {
  13052. Command._screenShaderData = new ShaderData();
  13053. Command._screenShader = Shader3D.find("BlitScreen");
  13054. }
  13055. run() {
  13056. }
  13057. recover() {
  13058. this._commandBuffer = null;
  13059. }
  13060. }
  13061. Command.SCREENTEXTURE_NAME = "u_MainTex";
  13062. Command.MAINTEXTURE_TEXELSIZE_NAME = "u_MainTex_TexelSize";
  13063. Command.SCREENTEXTURE_ID = Shader3D.propertyNameToID(Command.SCREENTEXTURE_NAME);
  13064. Command.MAINTEXTURE_TEXELSIZE_ID = Shader3D.propertyNameToID(Command.MAINTEXTURE_TEXELSIZE_NAME);
  13065. class BlitScreenQuadCMD extends Command {
  13066. constructor() {
  13067. super(...arguments);
  13068. this._source = null;
  13069. this._dest = null;
  13070. this._shader = null;
  13071. this._shaderData = null;
  13072. this._subShader = 0;
  13073. this._sourceTexelSize = new Vector4();
  13074. this._screenType = 0;
  13075. }
  13076. static create(source, dest, shader = null, shaderData = null, subShader = 0, screenType = BlitScreenQuadCMD._SCREENTYPE_QUAD) {
  13077. var cmd;
  13078. cmd = BlitScreenQuadCMD._pool.length > 0 ? BlitScreenQuadCMD._pool.pop() : new BlitScreenQuadCMD();
  13079. cmd._source = source;
  13080. cmd._dest = dest;
  13081. cmd._shader = shader;
  13082. cmd._shaderData = shaderData;
  13083. cmd._subShader = subShader;
  13084. cmd._screenType = screenType;
  13085. return cmd;
  13086. }
  13087. run() {
  13088. var shader = this._shader || Command._screenShader;
  13089. var shaderData = this._shaderData || Command._screenShaderData;
  13090. var dest = this._dest;
  13091. Laya.LayaGL.instance.viewport(0, 0, dest ? dest.width : RenderContext3D.clientWidth, dest ? dest.height : RenderContext3D.clientHeight);
  13092. shaderData.setTexture(Command.SCREENTEXTURE_ID, this._source);
  13093. this._sourceTexelSize.setValue(1.0 / this._source.width, 1.0 / this._source.height, this._source.width, this._source.height);
  13094. shaderData.setVector(Command.MAINTEXTURE_TEXELSIZE_ID, this._sourceTexelSize);
  13095. (dest) && (dest._start());
  13096. var subShader = shader.getSubShaderAt(this._subShader);
  13097. var passes = subShader._passes;
  13098. for (var i = 0, n = passes.length; i < n; i++) {
  13099. var comDef = BlitScreenQuadCMD._compileDefine;
  13100. shaderData._defineDatas.cloneTo(comDef);
  13101. var shaderPass = passes[i].withCompile(comDef);
  13102. shaderPass.bind();
  13103. shaderPass.uploadUniforms(shaderPass._materialUniformParamsMap, shaderData, true);
  13104. shaderPass.uploadRenderStateBlendDepth(shaderData);
  13105. shaderPass.uploadRenderStateFrontFace(shaderData, false, null);
  13106. switch (this._screenType) {
  13107. case BlitScreenQuadCMD._SCREENTYPE_QUAD:
  13108. dest ? ScreenQuad.instance.renderInvertUV() : ScreenQuad.instance.render();
  13109. break;
  13110. case BlitScreenQuadCMD._SCREENTYPE_TRIANGLE:
  13111. dest ? ScreenTriangle.instance.renderInvertUV() : ScreenTriangle.instance.render();
  13112. break;
  13113. throw "BlitScreenQuadCMD:unknown screen Type.";
  13114. }
  13115. }
  13116. (dest) && (dest._end());
  13117. }
  13118. recover() {
  13119. BlitScreenQuadCMD._pool.push(this);
  13120. this._dest = null;
  13121. this._shader = null;
  13122. this._shaderData = null;
  13123. super.recover();
  13124. }
  13125. }
  13126. BlitScreenQuadCMD._SCREENTYPE_QUAD = 0;
  13127. BlitScreenQuadCMD._SCREENTYPE_TRIANGLE = 1;
  13128. BlitScreenQuadCMD._compileDefine = new DefineDatas();
  13129. BlitScreenQuadCMD._pool = [];
  13130. class SetRenderTargetCMD extends Command {
  13131. constructor() {
  13132. super(...arguments);
  13133. this._renderTexture = null;
  13134. }
  13135. static create(renderTexture) {
  13136. var cmd;
  13137. cmd = SetRenderTargetCMD._pool.length > 0 ? SetRenderTargetCMD._pool.pop() : new SetRenderTargetCMD();
  13138. cmd._renderTexture = renderTexture;
  13139. return cmd;
  13140. }
  13141. run() {
  13142. this._renderTexture._start();
  13143. }
  13144. recover() {
  13145. SetRenderTargetCMD._pool.push(this);
  13146. this._renderTexture = null;
  13147. }
  13148. }
  13149. SetRenderTargetCMD._pool = [];
  13150. class SetShaderDataTextureCMD extends Command {
  13151. constructor() {
  13152. super(...arguments);
  13153. this._shaderData = null;
  13154. this._nameID = 0;
  13155. this._texture = null;
  13156. }
  13157. static create(shaderData, nameID, texture) {
  13158. var cmd;
  13159. cmd = SetShaderDataTextureCMD._pool.length > 0 ? SetShaderDataTextureCMD._pool.pop() : new SetShaderDataTextureCMD();
  13160. cmd._shaderData = shaderData;
  13161. cmd._nameID = nameID;
  13162. cmd._texture = texture;
  13163. return cmd;
  13164. }
  13165. run() {
  13166. this._shaderData.setTexture(this._nameID, this._texture);
  13167. }
  13168. recover() {
  13169. SetShaderDataTextureCMD._pool.push(this);
  13170. this._shaderData = null;
  13171. this._nameID = 0;
  13172. this._texture = null;
  13173. }
  13174. }
  13175. SetShaderDataTextureCMD._pool = [];
  13176. class CommandBuffer {
  13177. constructor() {
  13178. this._camera = null;
  13179. this._commands = [];
  13180. }
  13181. _apply() {
  13182. for (var i = 0, n = this._commands.length; i < n; i++)
  13183. this._commands[i].run();
  13184. }
  13185. setShaderDataTexture(shaderData, nameID, source) {
  13186. this._commands.push(SetShaderDataTextureCMD.create(shaderData, nameID, source));
  13187. }
  13188. blitScreenQuad(source, dest, shader = null, shaderData = null, subShader = 0) {
  13189. this._commands.push(BlitScreenQuadCMD.create(source, dest, shader, shaderData, subShader, BlitScreenQuadCMD._SCREENTYPE_QUAD));
  13190. }
  13191. blitScreenTriangle(source, dest, shader = null, shaderData = null, subShader = 0) {
  13192. this._commands.push(BlitScreenQuadCMD.create(source, dest, shader, shaderData, subShader, BlitScreenQuadCMD._SCREENTYPE_TRIANGLE));
  13193. }
  13194. setRenderTarget(renderTexture) {
  13195. this._commands.push(SetRenderTargetCMD.create(renderTexture));
  13196. }
  13197. clear() {
  13198. for (var i = 0, n = this._commands.length; i < n; i++)
  13199. this._commands[i].recover();
  13200. this._commands.length = 0;
  13201. }
  13202. }
  13203. class Camera extends BaseCamera {
  13204. constructor(aspectRatio = 0, nearPlane = 0.3, farPlane = 1000) {
  13205. super(nearPlane, farPlane);
  13206. this._updateViewMatrix = true;
  13207. this._postProcess = null;
  13208. this._enableHDR = false;
  13209. this._viewportParams = new Vector4();
  13210. this._projectionParams = new Vector4();
  13211. this._offScreenRenderTexture = null;
  13212. this._renderTexture = null;
  13213. this._postProcessCommandBuffers = [];
  13214. this._clusterPlaneCacheFlag = new Vector2(-1, -1);
  13215. this.enableRender = true;
  13216. this._viewMatrix = new Matrix4x4();
  13217. this._projectionMatrix = new Matrix4x4();
  13218. this._projectionViewMatrix = new Matrix4x4();
  13219. this._viewport = new Viewport(0, 0, 0, 0);
  13220. this._normalizedViewport = new Viewport(0, 0, 1, 1);
  13221. this._aspectRatio = aspectRatio;
  13222. this._boundFrustum = new BoundFrustum(Matrix4x4.DEFAULT);
  13223. if (Laya.Render.supportWebGLPlusCulling)
  13224. this._boundFrustumBuffer = new Float32Array(24);
  13225. this._calculateProjectionMatrix();
  13226. Laya.Laya.stage.on(Laya.Event.RESIZE, this, this._onScreenSizeChanged);
  13227. this.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  13228. }
  13229. get aspectRatio() {
  13230. if (this._aspectRatio === 0) {
  13231. var vp = this.viewport;
  13232. return vp.width / vp.height;
  13233. }
  13234. return this._aspectRatio;
  13235. }
  13236. set aspectRatio(value) {
  13237. if (value < 0)
  13238. throw new Error("Camera: the aspect ratio has to be a positive real number.");
  13239. this._aspectRatio = value;
  13240. this._calculateProjectionMatrix();
  13241. }
  13242. get viewport() {
  13243. if (this._offScreenRenderTexture)
  13244. this._calculationViewport(this._normalizedViewport, this._offScreenRenderTexture.width, this._offScreenRenderTexture.height);
  13245. else
  13246. this._calculationViewport(this._normalizedViewport, RenderContext3D.clientWidth, RenderContext3D.clientHeight);
  13247. return this._viewport;
  13248. }
  13249. set viewport(value) {
  13250. var width;
  13251. var height;
  13252. if (this._offScreenRenderTexture) {
  13253. width = this._offScreenRenderTexture.width;
  13254. height = this._offScreenRenderTexture.height;
  13255. }
  13256. else {
  13257. width = RenderContext3D.clientWidth;
  13258. height = RenderContext3D.clientHeight;
  13259. }
  13260. this._normalizedViewport.x = value.x / width;
  13261. this._normalizedViewport.y = value.y / height;
  13262. this._normalizedViewport.width = value.width / width;
  13263. this._normalizedViewport.height = value.height / height;
  13264. this._calculationViewport(this._normalizedViewport, width, height);
  13265. this._calculateProjectionMatrix();
  13266. }
  13267. get normalizedViewport() {
  13268. return this._normalizedViewport;
  13269. }
  13270. set normalizedViewport(value) {
  13271. var width;
  13272. var height;
  13273. if (this._offScreenRenderTexture) {
  13274. width = this._offScreenRenderTexture.width;
  13275. height = this._offScreenRenderTexture.height;
  13276. }
  13277. else {
  13278. width = RenderContext3D.clientWidth;
  13279. height = RenderContext3D.clientHeight;
  13280. }
  13281. if (this._normalizedViewport !== value)
  13282. value.cloneTo(this._normalizedViewport);
  13283. this._calculationViewport(value, width, height);
  13284. this._calculateProjectionMatrix();
  13285. }
  13286. get viewMatrix() {
  13287. if (this._updateViewMatrix) {
  13288. var scale = this.transform.getWorldLossyScale();
  13289. var scaleX = scale.x;
  13290. var scaleY = scale.y;
  13291. var scaleZ = scale.z;
  13292. var viewMatE = this._viewMatrix.elements;
  13293. this.transform.worldMatrix.cloneTo(this._viewMatrix);
  13294. viewMatE[0] /= scaleX;
  13295. viewMatE[1] /= scaleX;
  13296. viewMatE[2] /= scaleX;
  13297. viewMatE[4] /= scaleY;
  13298. viewMatE[5] /= scaleY;
  13299. viewMatE[6] /= scaleY;
  13300. viewMatE[8] /= scaleZ;
  13301. viewMatE[9] /= scaleZ;
  13302. viewMatE[10] /= scaleZ;
  13303. this._viewMatrix.invert(this._viewMatrix);
  13304. this._updateViewMatrix = false;
  13305. }
  13306. return this._viewMatrix;
  13307. }
  13308. get projectionMatrix() {
  13309. return this._projectionMatrix;
  13310. }
  13311. set projectionMatrix(value) {
  13312. this._projectionMatrix = value;
  13313. this._useUserProjectionMatrix = true;
  13314. }
  13315. get projectionViewMatrix() {
  13316. Matrix4x4.multiply(this.projectionMatrix, this.viewMatrix, this._projectionViewMatrix);
  13317. return this._projectionViewMatrix;
  13318. }
  13319. get boundFrustum() {
  13320. this._boundFrustum.matrix = this.projectionViewMatrix;
  13321. if (Laya.Render.supportWebGLPlusCulling) {
  13322. var near = this._boundFrustum.near;
  13323. var far = this._boundFrustum.far;
  13324. var left = this._boundFrustum.left;
  13325. var right = this._boundFrustum.right;
  13326. var top = this._boundFrustum.top;
  13327. var bottom = this._boundFrustum.bottom;
  13328. var nearNE = near.normal;
  13329. var farNE = far.normal;
  13330. var leftNE = left.normal;
  13331. var rightNE = right.normal;
  13332. var topNE = top.normal;
  13333. var bottomNE = bottom.normal;
  13334. var buffer = this._boundFrustumBuffer;
  13335. buffer[0] = nearNE.x, buffer[1] = nearNE.y, buffer[2] = nearNE.z, buffer[3] = near.distance;
  13336. buffer[4] = farNE.x, buffer[5] = farNE.y, buffer[6] = farNE.z, buffer[7] = far.distance;
  13337. buffer[8] = leftNE.x, buffer[9] = leftNE.y, buffer[10] = leftNE.z, buffer[11] = left.distance;
  13338. buffer[12] = rightNE.x, buffer[13] = rightNE.y, buffer[14] = rightNE.z, buffer[15] = right.distance;
  13339. buffer[16] = topNE.x, buffer[17] = topNE.y, buffer[18] = topNE.z, buffer[19] = top.distance;
  13340. buffer[20] = bottomNE.x, buffer[21] = bottomNE.y, buffer[22] = bottomNE.z, buffer[23] = bottom.distance;
  13341. }
  13342. return this._boundFrustum;
  13343. }
  13344. get renderTarget() {
  13345. return this._offScreenRenderTexture;
  13346. }
  13347. set renderTarget(value) {
  13348. if (this._offScreenRenderTexture !== value) {
  13349. this._offScreenRenderTexture = value;
  13350. this._calculateProjectionMatrix();
  13351. }
  13352. }
  13353. get postProcess() {
  13354. return this._postProcess;
  13355. }
  13356. set postProcess(value) {
  13357. this._postProcess = value;
  13358. var postProcessCommandBuffer = new CommandBuffer();
  13359. this.addCommandBuffer(Camera.CAMERAEVENT_POSTPROCESS, postProcessCommandBuffer);
  13360. value._init(this, postProcessCommandBuffer);
  13361. }
  13362. get enableHDR() {
  13363. return this._enableHDR;
  13364. }
  13365. set enableHDR(value) {
  13366. if (value) {
  13367. if (SystemUtils.supportRenderTextureFormat(Laya.RenderTextureFormat.R16G16B16A16))
  13368. this._enableHDR = true;
  13369. else
  13370. console.warn("Camera:can't enable HDR in this device.");
  13371. }
  13372. else {
  13373. this._enableHDR = false;
  13374. }
  13375. }
  13376. _calculationViewport(normalizedViewport, width, height) {
  13377. var lx = normalizedViewport.x * width;
  13378. var ly = normalizedViewport.y * height;
  13379. var rx = lx + Math.max(normalizedViewport.width * width, 0);
  13380. var ry = ly + Math.max(normalizedViewport.height * height, 0);
  13381. var ceilLeftX = Math.ceil(lx);
  13382. var ceilLeftY = Math.ceil(ly);
  13383. var floorRightX = Math.floor(rx);
  13384. var floorRightY = Math.floor(ry);
  13385. var pixelLeftX = ceilLeftX - lx >= 0.5 ? Math.floor(lx) : ceilLeftX;
  13386. var pixelLeftY = ceilLeftY - ly >= 0.5 ? Math.floor(ly) : ceilLeftY;
  13387. var pixelRightX = rx - floorRightX >= 0.5 ? Math.ceil(rx) : floorRightX;
  13388. var pixelRightY = ry - floorRightY >= 0.5 ? Math.ceil(ry) : floorRightY;
  13389. this._viewport.x = pixelLeftX;
  13390. this._viewport.y = pixelLeftY;
  13391. this._viewport.width = pixelRightX - pixelLeftX;
  13392. this._viewport.height = pixelRightY - pixelLeftY;
  13393. }
  13394. _calculateProjectionMatrix() {
  13395. if (!this._useUserProjectionMatrix) {
  13396. if (this._orthographic) {
  13397. var halfHeight = this.orthographicVerticalSize * 0.5;
  13398. var halfWidth = halfHeight * this.aspectRatio;
  13399. Matrix4x4.createOrthoOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, this.nearPlane, this.farPlane, this._projectionMatrix);
  13400. }
  13401. else {
  13402. Matrix4x4.createPerspective(3.1416 * this.fieldOfView / 180.0, this.aspectRatio, this.nearPlane, this.farPlane, this._projectionMatrix);
  13403. }
  13404. }
  13405. }
  13406. _isLayerVisible(layer) {
  13407. return (Math.pow(2, layer) & this.cullingMask) != 0;
  13408. }
  13409. _onTransformChanged(flag) {
  13410. flag &= Transform3D.TRANSFORM_WORLDMATRIX;
  13411. (flag) && (this._updateViewMatrix = true);
  13412. }
  13413. _parse(data, spriteMap) {
  13414. super._parse(data, spriteMap);
  13415. var viewport = data.viewport;
  13416. this.normalizedViewport = new Viewport(viewport[0], viewport[1], viewport[2], viewport[3]);
  13417. var enableHDR = data.enableHDR;
  13418. (enableHDR !== undefined) && (this.enableHDR = enableHDR);
  13419. }
  13420. _getCanvasHeight() {
  13421. if (this._offScreenRenderTexture)
  13422. return this._offScreenRenderTexture.height;
  13423. else
  13424. return RenderContext3D.clientHeight;
  13425. }
  13426. _getInternalRenderTexture() {
  13427. return this._renderTexture || this._offScreenRenderTexture;
  13428. }
  13429. _applyPostProcessCommandBuffers() {
  13430. for (var i = 0, n = this._postProcessCommandBuffers.length; i < n; i++)
  13431. this._postProcessCommandBuffers[i]._apply();
  13432. }
  13433. _getRenderTextureFormat() {
  13434. if (this._enableHDR)
  13435. return Laya.RenderTextureFormat.R16G16B16A16;
  13436. else
  13437. return Laya.RenderTextureFormat.R8G8B8;
  13438. }
  13439. _prepareCameraToRender() {
  13440. super._prepareCameraToRender();
  13441. var vp = this.viewport;
  13442. this._viewportParams.setValue(vp.x, vp.y, vp.width, vp.height);
  13443. this._projectionParams.setValue(this._nearPlane, this._farPlane, this._getInternalRenderTexture() ? -1 : 1, 0);
  13444. this._shaderValues.setVector(BaseCamera.VIEWPORT, this._viewportParams);
  13445. this._shaderValues.setVector(BaseCamera.PROJECTION_PARAMS, this._projectionParams);
  13446. }
  13447. _applyViewProject(context, viewMat, proMat, inverseY) {
  13448. var projectView;
  13449. var shaderData = this._shaderValues;
  13450. if (inverseY) {
  13451. Matrix4x4.multiply(BaseCamera._invertYScaleMatrix, proMat, BaseCamera._invertYProjectionMatrix);
  13452. Matrix4x4.multiply(BaseCamera._invertYProjectionMatrix, viewMat, BaseCamera._invertYProjectionViewMatrix);
  13453. proMat = BaseCamera._invertYProjectionMatrix;
  13454. projectView = BaseCamera._invertYProjectionViewMatrix;
  13455. }
  13456. else {
  13457. Matrix4x4.multiply(proMat, viewMat, this._projectionViewMatrix);
  13458. projectView = this._projectionViewMatrix;
  13459. }
  13460. context.viewMatrix = viewMat;
  13461. context.projectionMatrix = proMat;
  13462. context.projectionViewMatrix = projectView;
  13463. shaderData.setMatrix4x4(BaseCamera.VIEWMATRIX, viewMat);
  13464. shaderData.setMatrix4x4(BaseCamera.PROJECTMATRIX, proMat);
  13465. shaderData.setMatrix4x4(BaseCamera.VIEWPROJECTMATRIX, projectView);
  13466. }
  13467. _updateClusterPlaneXY() {
  13468. var fieldOfView = this.fieldOfView;
  13469. var aspectRatio = this.aspectRatio;
  13470. if (this._clusterPlaneCacheFlag.x !== fieldOfView || this._clusterPlaneCacheFlag.y !== aspectRatio) {
  13471. var clusterCount = Config3D._config.lightClusterCount;
  13472. var xSlixe = clusterCount.x, ySlice = clusterCount.y;
  13473. var xCount = xSlixe + 1, yCount = ySlice + 1;
  13474. var xPlanes = this._clusterXPlanes, yPlanes = this._clusterYPlanes;
  13475. if (!xPlanes) {
  13476. xPlanes = this._clusterXPlanes = new Array(xCount);
  13477. yPlanes = this._clusterYPlanes = new Array(yCount);
  13478. for (var i = 0; i < xCount; i++)
  13479. xPlanes[i] = new Vector3();
  13480. for (var i = 0; i < yCount; i++)
  13481. yPlanes[i] = new Vector3();
  13482. }
  13483. var halfY = Math.tan((this.fieldOfView / 2) * Math.PI / 180);
  13484. var halfX = this.aspectRatio * halfY;
  13485. var yLengthPerCluster = 2 * halfY / xSlixe;
  13486. var xLengthPerCluster = 2 * halfX / ySlice;
  13487. for (var i = 0; i < xCount; i++) {
  13488. var angle = -halfX + xLengthPerCluster * i;
  13489. var bigHypot = Math.sqrt(1 + angle * angle);
  13490. var normX = 1 / bigHypot;
  13491. var xPlane = xPlanes[i];
  13492. xPlane.setValue(normX, 0, -angle * normX);
  13493. }
  13494. for (var i = 0; i < yCount; i++) {
  13495. var angle = halfY - yLengthPerCluster * i;
  13496. var bigHypot = Math.sqrt(1 + angle * angle);
  13497. var normY = -1 / bigHypot;
  13498. var yPlane = yPlanes[i];
  13499. yPlane.setValue(0, normY, -angle * normY);
  13500. }
  13501. this._clusterPlaneCacheFlag.x = fieldOfView;
  13502. this._clusterPlaneCacheFlag.y = aspectRatio;
  13503. }
  13504. }
  13505. render(shader = null, replacementTag = null) {
  13506. if (!this._scene)
  13507. return;
  13508. var createRenderTexture = this._postProcess || this._enableHDR ? true : false;
  13509. if (createRenderTexture)
  13510. this._renderTexture = RenderTexture.createFromPool(RenderContext3D.clientWidth, RenderContext3D.clientHeight, this._getRenderTextureFormat(), Laya.RenderTextureDepthFormat.DEPTH_16, Laya.BaseTexture.FILTERMODE_BILINEAR);
  13511. var gl = Laya.LayaGL.instance;
  13512. var context = RenderContext3D._instance;
  13513. var scene = context.scene = this._scene;
  13514. if (scene.parallelSplitShadowMaps[0]) {
  13515. ShaderData.setRuntimeValueMode(false);
  13516. var parallelSplitShadowMap = scene.parallelSplitShadowMaps[0];
  13517. parallelSplitShadowMap._calcAllLightCameraInfo(this);
  13518. scene._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_CAST_SHADOW);
  13519. for (var i = 0, n = parallelSplitShadowMap.shadowMapCount; i < n; i++) {
  13520. var smCamera = parallelSplitShadowMap.cameras[i];
  13521. context.camera = smCamera;
  13522. FrustumCulling.renderObjectCulling(smCamera, scene, context, scene._castShadowRenders, shader, replacementTag);
  13523. var shadowMap = parallelSplitShadowMap.cameras[i + 1].renderTarget;
  13524. shadowMap._start();
  13525. context.camera = smCamera;
  13526. Camera._updateMark++;
  13527. context.viewport = smCamera.viewport;
  13528. smCamera._prepareCameraToRender();
  13529. smCamera._applyViewProject(context, smCamera.viewMatrix, smCamera.projectionMatrix, false);
  13530. scene._clear(gl, context);
  13531. var queue = scene._opaqueQueue;
  13532. queue._render(context, false);
  13533. shadowMap._end();
  13534. }
  13535. scene._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_CAST_SHADOW);
  13536. ShaderData.setRuntimeValueMode(true);
  13537. }
  13538. context.camera = this;
  13539. Camera._updateMark++;
  13540. scene._preRenderScript();
  13541. var renderTar = this._getInternalRenderTexture();
  13542. (renderTar) && (renderTar._start());
  13543. context.viewport = this.viewport;
  13544. this._prepareCameraToRender();
  13545. var multiLighting = Config3D._config._multiLighting;
  13546. (multiLighting) && (Cluster.instance.update(this, (this._scene)));
  13547. this._applyViewProject(context, this.viewMatrix, this._projectionMatrix, renderTar ? true : false);
  13548. scene._preCulling(context, this, shader, replacementTag);
  13549. scene._clear(gl, context);
  13550. scene._renderScene(context);
  13551. scene._postRenderScript();
  13552. (renderTar) && (renderTar._end());
  13553. if (createRenderTexture) {
  13554. if (this._postProcess) {
  13555. this._postProcess._render();
  13556. this._applyPostProcessCommandBuffers();
  13557. }
  13558. else if (this._enableHDR) {
  13559. var blit = BlitScreenQuadCMD.create(this._renderTexture, this._offScreenRenderTexture ? this._offScreenRenderTexture : null);
  13560. blit.run();
  13561. blit.recover();
  13562. }
  13563. RenderTexture.recoverToPool(this._renderTexture);
  13564. }
  13565. }
  13566. viewportPointToRay(point, out) {
  13567. Picker.calculateCursorRay(point, this.viewport, this._projectionMatrix, this.viewMatrix, null, out);
  13568. }
  13569. normalizedViewportPointToRay(point, out) {
  13570. var finalPoint = Camera._tempVector20;
  13571. var vp = this.viewport;
  13572. finalPoint.x = point.x * vp.width;
  13573. finalPoint.y = point.y * vp.height;
  13574. Picker.calculateCursorRay(finalPoint, this.viewport, this._projectionMatrix, this.viewMatrix, null, out);
  13575. }
  13576. worldToViewportPoint(position, out) {
  13577. Matrix4x4.multiply(this._projectionMatrix, this._viewMatrix, this._projectionViewMatrix);
  13578. this.viewport.project(position, this._projectionViewMatrix, out);
  13579. out.x = out.x / Laya.Laya.stage.clientScaleX;
  13580. out.y = out.y / Laya.Laya.stage.clientScaleY;
  13581. }
  13582. worldToNormalizedViewportPoint(position, out) {
  13583. Matrix4x4.multiply(this._projectionMatrix, this._viewMatrix, this._projectionViewMatrix);
  13584. this.normalizedViewport.project(position, this._projectionViewMatrix, out);
  13585. out.x = out.x / Laya.Laya.stage.clientScaleX;
  13586. out.y = out.y / Laya.Laya.stage.clientScaleY;
  13587. }
  13588. convertScreenCoordToOrthographicCoord(source, out) {
  13589. if (this._orthographic) {
  13590. var clientWidth = RenderContext3D.clientWidth;
  13591. var clientHeight = RenderContext3D.clientHeight;
  13592. var ratioX = this.orthographicVerticalSize * this.aspectRatio / clientWidth;
  13593. var ratioY = this.orthographicVerticalSize / clientHeight;
  13594. out.x = (-clientWidth / 2 + source.x * Laya.Laya.stage.clientScaleX) * ratioX;
  13595. out.y = (clientHeight / 2 - source.y * Laya.Laya.stage.clientScaleY) * ratioY;
  13596. out.z = (this.nearPlane - this.farPlane) * (source.z + 1) / 2 - this.nearPlane;
  13597. Vector3.transformCoordinate(out, this.transform.worldMatrix, out);
  13598. return true;
  13599. }
  13600. else {
  13601. return false;
  13602. }
  13603. }
  13604. destroy(destroyChild = true) {
  13605. this._offScreenRenderTexture = null;
  13606. this.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  13607. super.destroy(destroyChild);
  13608. }
  13609. addCommandBuffer(event, commandBuffer) {
  13610. switch (event) {
  13611. case Camera.CAMERAEVENT_POSTPROCESS:
  13612. this._postProcessCommandBuffers.push(commandBuffer);
  13613. commandBuffer._camera = this;
  13614. break;
  13615. default:
  13616. throw "Camera:unknown event.";
  13617. }
  13618. }
  13619. removeCommandBuffer(event, commandBuffer) {
  13620. switch (event) {
  13621. case Camera.CAMERAEVENT_POSTPROCESS:
  13622. var index = this._postProcessCommandBuffers.indexOf(commandBuffer);
  13623. if (index !== -1)
  13624. this._postProcessCommandBuffers.splice(index, 1);
  13625. break;
  13626. default:
  13627. throw "Camera:unknown event.";
  13628. }
  13629. }
  13630. removeCommandBuffers(event) {
  13631. switch (event) {
  13632. case Camera.CAMERAEVENT_POSTPROCESS:
  13633. this._postProcessCommandBuffers.length = 0;
  13634. break;
  13635. default:
  13636. throw "Camera:unknown event.";
  13637. }
  13638. }
  13639. _create() {
  13640. return new Camera();
  13641. }
  13642. }
  13643. Camera.CAMERAEVENT_POSTPROCESS = 0;
  13644. Camera._tempVector20 = new Vector2();
  13645. Camera._updateMark = 0;
  13646. class RenderElement {
  13647. constructor() {
  13648. this.renderSubShader = null;
  13649. this.renderType = RenderElement.RENDERTYPE_NORMAL;
  13650. }
  13651. getInvertFront() {
  13652. return this._transform._isFrontFaceInvert;
  13653. }
  13654. setTransform(transform) {
  13655. this._transform = transform;
  13656. }
  13657. setGeometry(geometry) {
  13658. this._geometry = geometry;
  13659. }
  13660. addToOpaqueRenderQueue(context, queue) {
  13661. queue.elements.add(this);
  13662. }
  13663. addToTransparentRenderQueue(context, queue) {
  13664. queue.elements.add(this);
  13665. queue.lastTransparentBatched = false;
  13666. queue.lastTransparentRenderElement = this;
  13667. }
  13668. _update(scene, context, customShader, replacementTag) {
  13669. if (this.material) {
  13670. var subShader = this.material._shader.getSubShaderAt(0);
  13671. this.renderSubShader = null;
  13672. if (customShader) {
  13673. if (replacementTag) {
  13674. var oriTag = subShader.getFlag(replacementTag);
  13675. if (oriTag) {
  13676. var customSubShaders = customShader._subShaders;
  13677. for (var k = 0, p = customSubShaders.length; k < p; k++) {
  13678. var customSubShader = customSubShaders[k];
  13679. if (oriTag === customSubShader.getFlag(replacementTag)) {
  13680. this.renderSubShader = customSubShader;
  13681. break;
  13682. }
  13683. }
  13684. if (!this.renderSubShader)
  13685. return;
  13686. }
  13687. else {
  13688. return;
  13689. }
  13690. }
  13691. else {
  13692. this.renderSubShader = customShader.getSubShaderAt(0);
  13693. }
  13694. }
  13695. else {
  13696. this.renderSubShader = subShader;
  13697. }
  13698. var renderQueue = scene._getRenderQueue(this.material.renderQueue);
  13699. if (renderQueue.isTransparent)
  13700. this.addToTransparentRenderQueue(context, renderQueue);
  13701. else
  13702. this.addToOpaqueRenderQueue(context, renderQueue);
  13703. }
  13704. }
  13705. _render(context, isTarget) {
  13706. var lastStateMaterial, lastStateShaderInstance, lastStateRender;
  13707. var updateMark = Camera._updateMark;
  13708. var scene = context.scene;
  13709. var camera = context.camera;
  13710. var transform = this._transform;
  13711. var geometry = this._geometry;
  13712. context.renderElement = this;
  13713. var updateRender = updateMark !== this.render._updateMark || this.renderType !== this.render._updateRenderType;
  13714. if (updateRender) {
  13715. this.render._renderUpdate(context, transform);
  13716. this.render._renderUpdateWithCamera(context, transform);
  13717. this.render._updateMark = updateMark;
  13718. this.render._updateRenderType = this.renderType;
  13719. }
  13720. else {
  13721. if (this.renderType == RenderElement.RENDERTYPE_INSTANCEBATCH) {
  13722. this.render._renderUpdate(context, transform);
  13723. this.render._renderUpdateWithCamera(context, transform);
  13724. }
  13725. }
  13726. if (geometry._prepareRender(context)) {
  13727. var passes = this.renderSubShader._passes;
  13728. for (var j = 0, m = passes.length; j < m; j++) {
  13729. var comDef = RenderElement._compileDefine;
  13730. scene._shaderValues._defineDatas.cloneTo(comDef);
  13731. comDef.removeDefineDatas(this.material._disablePublicDefineDatas);
  13732. comDef.addDefineDatas(this.render._shaderValues._defineDatas);
  13733. comDef.addDefineDatas(this.material._shaderValues._defineDatas);
  13734. var shaderIns = context.shader = passes[j].withCompile(comDef);
  13735. var switchShader = shaderIns.bind();
  13736. var switchUpdateMark = (updateMark !== shaderIns._uploadMark);
  13737. var uploadScene = (shaderIns._uploadScene !== scene) || switchUpdateMark;
  13738. if (uploadScene || switchShader) {
  13739. shaderIns.uploadUniforms(shaderIns._sceneUniformParamsMap, scene._shaderValues, uploadScene);
  13740. shaderIns._uploadScene = scene;
  13741. }
  13742. var uploadSprite3D = (shaderIns._uploadRender !== this.render || shaderIns._uploadRenderType !== this.renderType) || switchUpdateMark;
  13743. if (uploadSprite3D || switchShader) {
  13744. shaderIns.uploadUniforms(shaderIns._spriteUniformParamsMap, this.render._shaderValues, uploadSprite3D);
  13745. shaderIns._uploadRender = this.render;
  13746. shaderIns._uploadRenderType = this.renderType;
  13747. }
  13748. var uploadCamera = shaderIns._uploadCamera !== camera || switchUpdateMark;
  13749. if (uploadCamera || switchShader) {
  13750. shaderIns.uploadUniforms(shaderIns._cameraUniformParamsMap, camera._shaderValues, uploadCamera);
  13751. shaderIns._uploadCamera = camera;
  13752. }
  13753. var uploadMaterial = (shaderIns._uploadMaterial !== this.material) || switchUpdateMark;
  13754. if (uploadMaterial || switchShader) {
  13755. shaderIns.uploadUniforms(shaderIns._materialUniformParamsMap, this.material._shaderValues, uploadMaterial);
  13756. shaderIns._uploadMaterial = this.material;
  13757. }
  13758. var matValues = this.material._shaderValues;
  13759. if (lastStateMaterial !== this.material || lastStateShaderInstance !== shaderIns) {
  13760. shaderIns.uploadRenderStateBlendDepth(matValues);
  13761. shaderIns.uploadRenderStateFrontFace(matValues, isTarget, this.getInvertFront());
  13762. lastStateMaterial = this.material;
  13763. lastStateShaderInstance = shaderIns;
  13764. lastStateRender = this.render;
  13765. }
  13766. else {
  13767. if (lastStateRender !== this.render) {
  13768. shaderIns.uploadRenderStateFrontFace(matValues, isTarget, this.getInvertFront());
  13769. lastStateRender = this.render;
  13770. }
  13771. }
  13772. geometry._render(context);
  13773. shaderIns._uploadMark = updateMark;
  13774. }
  13775. }
  13776. if (updateRender && this.renderType !== RenderElement.RENDERTYPE_NORMAL)
  13777. this.render._revertBatchRenderUpdate(context);
  13778. }
  13779. destroy() {
  13780. this._transform = null;
  13781. this._geometry = null;
  13782. this.material = null;
  13783. this.render = null;
  13784. }
  13785. }
  13786. RenderElement.RENDERTYPE_NORMAL = 0;
  13787. RenderElement.RENDERTYPE_STATICBATCH = 1;
  13788. RenderElement.RENDERTYPE_INSTANCEBATCH = 2;
  13789. RenderElement.RENDERTYPE_VERTEXBATCH = 3;
  13790. RenderElement._compileDefine = new DefineDatas();
  13791. class SubMeshRenderElement extends RenderElement {
  13792. constructor() {
  13793. super();
  13794. this._dynamicWorldPositionNormalNeedUpdate = true;
  13795. }
  13796. _onWorldMatrixChanged() {
  13797. this._dynamicWorldPositionNormalNeedUpdate = true;
  13798. }
  13799. _computeWorldPositionsAndNormals(positionOffset, normalOffset, multiSubMesh, vertexCount) {
  13800. if (this._dynamicWorldPositionNormalNeedUpdate) {
  13801. var subMesh = this._geometry;
  13802. var vertexBuffer = subMesh._vertexBuffer;
  13803. var vertexFloatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  13804. var oriVertexes = vertexBuffer.getFloat32Data();
  13805. var worldMat = this._transform.worldMatrix;
  13806. var rotation = this._transform.rotation;
  13807. var indices = subMesh._indices;
  13808. for (var i = 0; i < vertexCount; i++) {
  13809. var index = multiSubMesh ? indices[i] : i;
  13810. var oriOffset = index * vertexFloatCount;
  13811. var bakeOffset = i * 3;
  13812. Utils3D.transformVector3ArrayToVector3ArrayCoordinate(oriVertexes, oriOffset + positionOffset, worldMat, this._dynamicWorldPositions, bakeOffset);
  13813. (normalOffset !== -1) && (Utils3D.transformVector3ArrayByQuat(oriVertexes, oriOffset + normalOffset, rotation, this._dynamicWorldNormals, bakeOffset));
  13814. }
  13815. this._dynamicWorldPositionNormalNeedUpdate = false;
  13816. }
  13817. }
  13818. setTransform(transform) {
  13819. if (this._transform !== transform) {
  13820. (this._transform) && (this._transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatrixChanged));
  13821. (transform) && (transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatrixChanged));
  13822. this._dynamicWorldPositionNormalNeedUpdate = true;
  13823. this._transform = transform;
  13824. }
  13825. }
  13826. setGeometry(geometry) {
  13827. if (this._geometry !== geometry) {
  13828. var subMesh = geometry;
  13829. var mesh = subMesh._mesh;
  13830. if (mesh) {
  13831. var multiSubMesh = mesh._subMeshes.length > 1;
  13832. var dynBatVerCount = multiSubMesh ? subMesh._indexCount : mesh._vertexCount;
  13833. if (dynBatVerCount <= ILaya3D.SubMeshDynamicBatch.maxAllowVertexCount) {
  13834. var length = dynBatVerCount * 3;
  13835. this._dynamicVertexBatch = true;
  13836. this._dynamicWorldPositions = new Float32Array(length);
  13837. this._dynamicWorldNormals = new Float32Array(length);
  13838. this._dynamicVertexCount = dynBatVerCount;
  13839. this._dynamicMultiSubMesh = multiSubMesh;
  13840. }
  13841. else {
  13842. this._dynamicVertexBatch = false;
  13843. }
  13844. }
  13845. this._geometry = geometry;
  13846. }
  13847. }
  13848. addToOpaqueRenderQueue(context, queue) {
  13849. var subMeshStaticBatch = this.staticBatch;
  13850. var queueElements = queue.elements;
  13851. var elements = queueElements.elements;
  13852. if (subMeshStaticBatch) {
  13853. var staManager = ILaya3D.MeshRenderStaticBatchManager.instance;
  13854. var staBatchMarks = staManager.getBatchOpaquaMark(this.render.lightmapIndex + 1, this.render.receiveShadow, this.material.id, subMeshStaticBatch._batchID);
  13855. if (staManager._updateCountMark === staBatchMarks.updateMark) {
  13856. var staBatchIndex = staBatchMarks.indexInList;
  13857. if (staBatchMarks.batched) {
  13858. elements[staBatchIndex].staticBatchElementList.add(this);
  13859. }
  13860. else {
  13861. var staOriElement = elements[staBatchIndex];
  13862. var staOriRender = staOriElement.render;
  13863. var staBatchElement = staManager._getBatchRenderElementFromPool();
  13864. staBatchElement.renderType = RenderElement.RENDERTYPE_STATICBATCH;
  13865. staBatchElement.setGeometry(subMeshStaticBatch);
  13866. staBatchElement.material = staOriElement.material;
  13867. var staRootOwner = subMeshStaticBatch.batchOwner;
  13868. var staBatchTransform = staRootOwner ? staRootOwner._transform : null;
  13869. staBatchElement.setTransform(staBatchTransform);
  13870. staBatchElement.render = staOriRender;
  13871. staBatchElement.renderSubShader = staOriElement.renderSubShader;
  13872. var staBatchList = staBatchElement.staticBatchElementList;
  13873. staBatchList.length = 0;
  13874. staBatchList.add(staOriElement);
  13875. staBatchList.add(this);
  13876. elements[staBatchIndex] = staBatchElement;
  13877. staBatchMarks.batched = true;
  13878. }
  13879. }
  13880. else {
  13881. staBatchMarks.updateMark = staManager._updateCountMark;
  13882. staBatchMarks.indexInList = queueElements.length;
  13883. staBatchMarks.batched = false;
  13884. queueElements.add(this);
  13885. }
  13886. }
  13887. else if (this.renderSubShader._owner._enableInstancing && Laya.LayaGL.layaGPUInstance.supportInstance() && this.render.lightmapIndex < 0) {
  13888. var subMesh = this._geometry;
  13889. var insManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  13890. var insBatchMarks = insManager.getInstanceBatchOpaquaMark(this.render.receiveShadow, this.material.id, subMesh._id, this._transform._isFrontFaceInvert);
  13891. if (insManager._updateCountMark === insBatchMarks.updateMark) {
  13892. var insBatchIndex = insBatchMarks.indexInList;
  13893. if (insBatchMarks.batched) {
  13894. var instanceBatchElementList = elements[insBatchIndex].instanceBatchElementList;
  13895. if (instanceBatchElementList.length === SubMeshInstanceBatch.instance.maxInstanceCount) {
  13896. insBatchMarks.updateMark = insManager._updateCountMark;
  13897. insBatchMarks.indexInList = queueElements.length;
  13898. insBatchMarks.batched = false;
  13899. queueElements.add(this);
  13900. }
  13901. else {
  13902. instanceBatchElementList.add(this);
  13903. }
  13904. }
  13905. else {
  13906. var insOriElement = elements[insBatchIndex];
  13907. var insOriRender = insOriElement.render;
  13908. var insBatchElement = insManager._getBatchRenderElementFromPool();
  13909. insBatchElement.renderType = RenderElement.RENDERTYPE_INSTANCEBATCH;
  13910. insBatchElement.setGeometry(SubMeshInstanceBatch.instance);
  13911. insBatchElement.material = insOriElement.material;
  13912. insBatchElement.setTransform(null);
  13913. insBatchElement.render = insOriRender;
  13914. insBatchElement.instanceSubMesh = subMesh;
  13915. insBatchElement.renderSubShader = insOriElement.renderSubShader;
  13916. var insBatchList = insBatchElement.instanceBatchElementList;
  13917. insBatchList.length = 0;
  13918. insBatchList.add(insOriElement);
  13919. insBatchList.add(this);
  13920. elements[insBatchIndex] = insBatchElement;
  13921. insBatchMarks.batched = true;
  13922. }
  13923. }
  13924. else {
  13925. insBatchMarks.updateMark = insManager._updateCountMark;
  13926. insBatchMarks.indexInList = queueElements.length;
  13927. insBatchMarks.batched = false;
  13928. queueElements.add(this);
  13929. }
  13930. }
  13931. else if (this._dynamicVertexBatch) {
  13932. var verDec = this._geometry._vertexBuffer.vertexDeclaration;
  13933. var dynManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  13934. var dynBatchMarks = dynManager.getVertexBatchOpaquaMark(this.render.lightmapIndex + 1, this.render.receiveShadow, this.material.id, verDec.id);
  13935. if (dynManager._updateCountMark === dynBatchMarks.updateMark) {
  13936. var dynBatchIndex = dynBatchMarks.indexInList;
  13937. if (dynBatchMarks.batched) {
  13938. elements[dynBatchIndex].vertexBatchElementList.add(this);
  13939. }
  13940. else {
  13941. var dynOriElement = elements[dynBatchIndex];
  13942. var dynOriRender = dynOriElement.render;
  13943. var dynBatchElement = dynManager._getBatchRenderElementFromPool();
  13944. dynBatchElement.renderType = RenderElement.RENDERTYPE_VERTEXBATCH;
  13945. dynBatchElement.setGeometry(ILaya3D.SubMeshDynamicBatch.instance);
  13946. dynBatchElement.material = dynOriElement.material;
  13947. dynBatchElement.setTransform(null);
  13948. dynBatchElement.render = dynOriRender;
  13949. dynBatchElement.vertexBatchVertexDeclaration = verDec;
  13950. dynBatchElement.renderSubShader = dynOriElement.renderSubShader;
  13951. var dynBatchList = dynBatchElement.vertexBatchElementList;
  13952. dynBatchList.length = 0;
  13953. dynBatchList.add(dynOriElement);
  13954. dynBatchList.add(this);
  13955. elements[dynBatchIndex] = dynBatchElement;
  13956. dynBatchMarks.batched = true;
  13957. }
  13958. }
  13959. else {
  13960. dynBatchMarks.updateMark = dynManager._updateCountMark;
  13961. dynBatchMarks.indexInList = queueElements.length;
  13962. dynBatchMarks.batched = false;
  13963. queueElements.add(this);
  13964. }
  13965. }
  13966. else {
  13967. queueElements.add(this);
  13968. }
  13969. }
  13970. addToTransparentRenderQueue(context, queue) {
  13971. var subMeshStaticBatch = this.staticBatch;
  13972. var queueElements = queue.elements;
  13973. var elements = queueElements.elements;
  13974. if (subMeshStaticBatch) {
  13975. var staManager = ILaya3D.MeshRenderStaticBatchManager.instance;
  13976. var staLastElement = queue.lastTransparentRenderElement;
  13977. if (staLastElement) {
  13978. var staLastRender = staLastElement.render;
  13979. if (staLastElement._geometry._getType() !== this._geometry._getType() || staLastElement.staticBatch !== subMeshStaticBatch || staLastElement.material !== this.material || staLastRender.receiveShadow !== this.render.receiveShadow || staLastRender.lightmapIndex !== this.render.lightmapIndex) {
  13980. queueElements.add(this);
  13981. queue.lastTransparentBatched = false;
  13982. }
  13983. else {
  13984. if (queue.lastTransparentBatched) {
  13985. elements[queueElements.length - 1].staticBatchElementList.add((this));
  13986. }
  13987. else {
  13988. var staBatchElement = staManager._getBatchRenderElementFromPool();
  13989. staBatchElement.renderType = RenderElement.RENDERTYPE_STATICBATCH;
  13990. staBatchElement.setGeometry(subMeshStaticBatch);
  13991. staBatchElement.material = staLastElement.material;
  13992. var staRootOwner = subMeshStaticBatch.batchOwner;
  13993. var staBatchTransform = staRootOwner ? staRootOwner._transform : null;
  13994. staBatchElement.setTransform(staBatchTransform);
  13995. staBatchElement.render = this.render;
  13996. staBatchElement.renderSubShader = staLastElement.renderSubShader;
  13997. var staBatchList = staBatchElement.staticBatchElementList;
  13998. staBatchList.length = 0;
  13999. staBatchList.add(staLastElement);
  14000. staBatchList.add(this);
  14001. elements[queueElements.length - 1] = staBatchElement;
  14002. }
  14003. queue.lastTransparentBatched = true;
  14004. }
  14005. }
  14006. else {
  14007. queueElements.add(this);
  14008. queue.lastTransparentBatched = false;
  14009. }
  14010. }
  14011. else if (this.renderSubShader._owner._enableInstancing && Laya.LayaGL.layaGPUInstance.supportInstance() && this.render.lightmapIndex < 0) {
  14012. var subMesh = this._geometry;
  14013. var insManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  14014. var insLastElement = queue.lastTransparentRenderElement;
  14015. if (insLastElement) {
  14016. var insLastRender = insLastElement.render;
  14017. if (insLastElement._geometry._getType() !== this._geometry._getType() || insLastElement._geometry !== subMesh || insLastElement.material !== this.material || insLastRender.receiveShadow !== this.render.receiveShadow) {
  14018. queueElements.add(this);
  14019. queue.lastTransparentBatched = false;
  14020. }
  14021. else {
  14022. if (queue.lastTransparentBatched) {
  14023. var instanceBatchElementList = elements[queueElements.length - 1].instanceBatchElementList;
  14024. if (instanceBatchElementList.length === SubMeshInstanceBatch.instance.maxInstanceCount) {
  14025. queueElements.add(this);
  14026. queue.lastTransparentBatched = false;
  14027. }
  14028. else {
  14029. instanceBatchElementList.add(this);
  14030. queue.lastTransparentBatched = true;
  14031. }
  14032. }
  14033. else {
  14034. var insBatchElement = insManager._getBatchRenderElementFromPool();
  14035. insBatchElement.renderType = RenderElement.RENDERTYPE_INSTANCEBATCH;
  14036. insBatchElement.setGeometry(SubMeshInstanceBatch.instance);
  14037. insBatchElement.material = insLastElement.material;
  14038. insBatchElement.setTransform(null);
  14039. insBatchElement.render = this.render;
  14040. insBatchElement.instanceSubMesh = subMesh;
  14041. insBatchElement.renderSubShader = insLastElement.renderSubShader;
  14042. var insBatchList = insBatchElement.instanceBatchElementList;
  14043. insBatchList.length = 0;
  14044. insBatchList.add(insLastElement);
  14045. insBatchList.add(this);
  14046. elements[queueElements.length - 1] = insBatchElement;
  14047. queue.lastTransparentBatched = true;
  14048. }
  14049. }
  14050. }
  14051. else {
  14052. queueElements.add(this);
  14053. queue.lastTransparentBatched = false;
  14054. }
  14055. }
  14056. else if (this._dynamicVertexBatch) {
  14057. var verDec = this._geometry._vertexBuffer.vertexDeclaration;
  14058. var dynManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  14059. var dynLastElement = queue.lastTransparentRenderElement;
  14060. if (dynLastElement) {
  14061. var dynLastRender = dynLastElement.render;
  14062. if (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) {
  14063. queueElements.add(this);
  14064. queue.lastTransparentBatched = false;
  14065. }
  14066. else {
  14067. if (queue.lastTransparentBatched) {
  14068. elements[queueElements.length - 1].vertexBatchElementList.add((this));
  14069. }
  14070. else {
  14071. var dynBatchElement = dynManager._getBatchRenderElementFromPool();
  14072. dynBatchElement.renderType = RenderElement.RENDERTYPE_VERTEXBATCH;
  14073. dynBatchElement.setGeometry(ILaya3D.SubMeshDynamicBatch.instance);
  14074. dynBatchElement.material = dynLastElement.material;
  14075. dynBatchElement.setTransform(null);
  14076. dynBatchElement.render = this.render;
  14077. dynBatchElement.vertexBatchVertexDeclaration = verDec;
  14078. dynBatchElement.renderSubShader = dynLastElement.renderSubShader;
  14079. var dynBatchList = dynBatchElement.vertexBatchElementList;
  14080. dynBatchList.length = 0;
  14081. dynBatchList.add(dynLastElement);
  14082. dynBatchList.add(this);
  14083. elements[queueElements.length - 1] = dynBatchElement;
  14084. }
  14085. queue.lastTransparentBatched = true;
  14086. }
  14087. }
  14088. else {
  14089. queueElements.add(this);
  14090. queue.lastTransparentBatched = false;
  14091. }
  14092. }
  14093. else {
  14094. queueElements.add(this);
  14095. }
  14096. queue.lastTransparentRenderElement = this;
  14097. }
  14098. getInvertFront() {
  14099. switch (this.renderType) {
  14100. case RenderElement.RENDERTYPE_NORMAL:
  14101. return this._transform._isFrontFaceInvert;
  14102. case RenderElement.RENDERTYPE_STATICBATCH:
  14103. case RenderElement.RENDERTYPE_VERTEXBATCH:
  14104. return false;
  14105. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  14106. return this.instanceBatchElementList.elements[0]._transform._isFrontFaceInvert;
  14107. default:
  14108. throw "SubMeshRenderElement: unknown renderType";
  14109. }
  14110. }
  14111. destroy() {
  14112. super.destroy();
  14113. this._dynamicWorldPositions = null;
  14114. this._dynamicWorldNormals = null;
  14115. this.staticBatch = null;
  14116. this.staticBatchElementList = null;
  14117. this.vertexBatchElementList = null;
  14118. this.vertexBatchVertexDeclaration = null;
  14119. }
  14120. }
  14121. class SubMeshStaticBatch extends GeometryElement {
  14122. constructor(batchOwner, vertexDeclaration) {
  14123. super();
  14124. this._bufferState = new BufferState();
  14125. this._batchID = SubMeshStaticBatch._batchIDCounter++;
  14126. this._batchElements = [];
  14127. this._currentBatchVertexCount = 0;
  14128. this._currentBatchIndexCount = 0;
  14129. this._vertexDeclaration = vertexDeclaration;
  14130. this.batchOwner = batchOwner;
  14131. }
  14132. _getStaticBatchBakedVertexs(batchVertices, batchOffset, batchOwnerTransform, transform, render, mesh) {
  14133. var vertexBuffer = mesh._vertexBuffer;
  14134. var vertexDeclaration = vertexBuffer.vertexDeclaration;
  14135. var positionOffset = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  14136. var normalElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_NORMAL0);
  14137. var normalOffset = normalElement ? normalElement._offset / 4 : -1;
  14138. var colorElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  14139. var colorOffset = colorElement ? colorElement._offset / 4 : -1;
  14140. var uv0Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  14141. var uv0Offset = uv0Element ? uv0Element._offset / 4 : -1;
  14142. var uv1Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE1);
  14143. var uv1Offset = uv1Element ? uv1Element._offset / 4 : -1;
  14144. var tangentElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TANGENT0);
  14145. var sTangentOffset = tangentElement ? tangentElement._offset / 4 : -1;
  14146. var bakeVertexFloatCount = 18;
  14147. var oriVertexFloatCount = vertexDeclaration.vertexStride / 4;
  14148. var oriVertexes = vertexBuffer.getFloat32Data();
  14149. var worldMat;
  14150. if (batchOwnerTransform) {
  14151. var rootMat = batchOwnerTransform.worldMatrix;
  14152. rootMat.invert(SubMeshStaticBatch._tempMatrix4x40);
  14153. worldMat = SubMeshStaticBatch._tempMatrix4x41;
  14154. Matrix4x4.multiply(SubMeshStaticBatch._tempMatrix4x40, transform.worldMatrix, worldMat);
  14155. }
  14156. else {
  14157. worldMat = transform.worldMatrix;
  14158. }
  14159. var rotation = SubMeshStaticBatch._tempQuaternion0;
  14160. worldMat.decomposeTransRotScale(SubMeshStaticBatch._tempVector30, rotation, SubMeshStaticBatch._tempVector31);
  14161. var lightmapScaleOffset = render.lightmapScaleOffset;
  14162. var vertexCount = mesh.vertexCount;
  14163. for (var i = 0; i < vertexCount; i++) {
  14164. var oriOffset = i * oriVertexFloatCount;
  14165. var bakeOffset = (i + batchOffset) * bakeVertexFloatCount;
  14166. Utils3D.transformVector3ArrayToVector3ArrayCoordinate(oriVertexes, oriOffset + positionOffset, worldMat, batchVertices, bakeOffset + 0);
  14167. if (normalOffset !== -1)
  14168. Utils3D.transformVector3ArrayByQuat(oriVertexes, oriOffset + normalOffset, rotation, batchVertices, bakeOffset + 3);
  14169. var j, m;
  14170. var bakOff = bakeOffset + 6;
  14171. if (colorOffset !== -1) {
  14172. var oriOff = oriOffset + colorOffset;
  14173. for (j = 0, m = 4; j < m; j++)
  14174. batchVertices[bakOff + j] = oriVertexes[oriOff + j];
  14175. }
  14176. else {
  14177. for (j = 0, m = 4; j < m; j++)
  14178. batchVertices[bakOff + j] = 1.0;
  14179. }
  14180. if (uv0Offset !== -1) {
  14181. var absUv0Offset = oriOffset + uv0Offset;
  14182. batchVertices[bakeOffset + 10] = oriVertexes[absUv0Offset];
  14183. batchVertices[bakeOffset + 11] = oriVertexes[absUv0Offset + 1];
  14184. }
  14185. if (lightmapScaleOffset) {
  14186. if (uv1Offset !== -1)
  14187. Utils3D.transformLightingMapTexcoordArray(oriVertexes, oriOffset + uv1Offset, lightmapScaleOffset, batchVertices, bakeOffset + 12);
  14188. else
  14189. Utils3D.transformLightingMapTexcoordArray(oriVertexes, oriOffset + uv0Offset, lightmapScaleOffset, batchVertices, bakeOffset + 12);
  14190. }
  14191. if (sTangentOffset !== -1) {
  14192. var absSTanegntOffset = oriOffset + sTangentOffset;
  14193. batchVertices[bakeOffset + 14] = oriVertexes[absSTanegntOffset];
  14194. batchVertices[bakeOffset + 15] = oriVertexes[absSTanegntOffset + 1];
  14195. batchVertices[bakeOffset + 16] = oriVertexes[absSTanegntOffset + 2];
  14196. batchVertices[bakeOffset + 17] = oriVertexes[absSTanegntOffset + 3];
  14197. }
  14198. }
  14199. return vertexCount;
  14200. }
  14201. addTest(sprite) {
  14202. var vertexCount;
  14203. var subMeshVertexCount = sprite.meshFilter.sharedMesh.vertexCount;
  14204. vertexCount = this._currentBatchVertexCount + subMeshVertexCount;
  14205. if (vertexCount > SubMeshStaticBatch.maxBatchVertexCount)
  14206. return false;
  14207. return true;
  14208. }
  14209. add(sprite) {
  14210. var mesh = sprite.meshFilter.sharedMesh;
  14211. var subMeshVertexCount = mesh.vertexCount;
  14212. this._batchElements.push(sprite);
  14213. var render = sprite._render;
  14214. render._isPartOfStaticBatch = true;
  14215. render._staticBatch = this;
  14216. var renderElements = render._renderElements;
  14217. for (var i = 0, n = renderElements.length; i < n; i++)
  14218. renderElements[i].staticBatch = this;
  14219. this._currentBatchIndexCount += mesh._indexBuffer.indexCount;
  14220. this._currentBatchVertexCount += subMeshVertexCount;
  14221. }
  14222. remove(sprite) {
  14223. var mesh = sprite.meshFilter.sharedMesh;
  14224. var index = this._batchElements.indexOf(sprite);
  14225. if (index !== -1) {
  14226. this._batchElements.splice(index, 1);
  14227. var renderElements = sprite._render._renderElements;
  14228. for (var i = 0, n = renderElements.length; i < n; i++)
  14229. renderElements[i].staticBatch = null;
  14230. this._currentBatchIndexCount = this._currentBatchIndexCount - mesh._indexBuffer.indexCount;
  14231. this._currentBatchVertexCount = this._currentBatchVertexCount - mesh.vertexCount;
  14232. sprite._render._isPartOfStaticBatch = false;
  14233. }
  14234. }
  14235. finishInit() {
  14236. if (this._vertexBuffer) {
  14237. this._vertexBuffer.destroy();
  14238. this._indexBuffer.destroy();
  14239. Laya.Resource._addGPUMemory(-(this._vertexBuffer._byteLength + this._indexBuffer._byteLength));
  14240. }
  14241. var gl = Laya.LayaGL.instance;
  14242. var batchVertexCount = 0;
  14243. var batchIndexCount = 0;
  14244. var rootOwner = this.batchOwner;
  14245. var floatStride = this._vertexDeclaration.vertexStride / 4;
  14246. var vertexDatas = new Float32Array(floatStride * this._currentBatchVertexCount);
  14247. var indexDatas = new Uint16Array(this._currentBatchIndexCount);
  14248. this._vertexBuffer = new VertexBuffer3D(this._vertexDeclaration.vertexStride * this._currentBatchVertexCount, gl.STATIC_DRAW);
  14249. this._vertexBuffer.vertexDeclaration = this._vertexDeclaration;
  14250. this._indexBuffer = new IndexBuffer3D(IndexBuffer3D.INDEXTYPE_USHORT, this._currentBatchIndexCount, gl.STATIC_DRAW);
  14251. for (var i = 0, n = this._batchElements.length; i < n; i++) {
  14252. var sprite = this._batchElements[i];
  14253. var mesh = sprite.meshFilter.sharedMesh;
  14254. var meshVerCount = this._getStaticBatchBakedVertexs(vertexDatas, batchVertexCount, rootOwner ? rootOwner._transform : null, sprite._transform, sprite._render, mesh);
  14255. var indices = mesh._indexBuffer.getData();
  14256. var indexOffset = batchVertexCount;
  14257. var indexEnd = batchIndexCount + indices.length;
  14258. var elements = sprite._render._renderElements;
  14259. for (var j = 0, m = mesh.subMeshCount; j < m; j++) {
  14260. var subMesh = mesh._subMeshes[j];
  14261. var start = batchIndexCount + subMesh._indexStart;
  14262. var element = elements[j];
  14263. element.staticBatchIndexStart = start;
  14264. element.staticBatchIndexEnd = start + subMesh._indexCount;
  14265. }
  14266. indexDatas.set(indices, batchIndexCount);
  14267. var k;
  14268. var isInvert = rootOwner ? (sprite._transform._isFrontFaceInvert !== rootOwner.transform._isFrontFaceInvert) : sprite._transform._isFrontFaceInvert;
  14269. if (isInvert) {
  14270. for (k = batchIndexCount; k < indexEnd; k += 3) {
  14271. indexDatas[k] = indexOffset + indexDatas[k];
  14272. var index1 = indexDatas[k + 1];
  14273. var index2 = indexDatas[k + 2];
  14274. indexDatas[k + 1] = indexOffset + index2;
  14275. indexDatas[k + 2] = indexOffset + index1;
  14276. }
  14277. }
  14278. else {
  14279. for (k = batchIndexCount; k < indexEnd; k += 3) {
  14280. indexDatas[k] = indexOffset + indexDatas[k];
  14281. indexDatas[k + 1] = indexOffset + indexDatas[k + 1];
  14282. indexDatas[k + 2] = indexOffset + indexDatas[k + 2];
  14283. }
  14284. }
  14285. batchIndexCount += indices.length;
  14286. batchVertexCount += meshVerCount;
  14287. }
  14288. this._vertexBuffer.setData(vertexDatas.buffer);
  14289. this._indexBuffer.setData(indexDatas);
  14290. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  14291. Laya.Resource._addGPUMemory(memorySize);
  14292. this._bufferState.bind();
  14293. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  14294. this._bufferState.applyIndexBuffer(this._indexBuffer);
  14295. this._bufferState.unBind();
  14296. }
  14297. _render(state) {
  14298. this._bufferState.bind();
  14299. var gl = Laya.LayaGL.instance;
  14300. var element = state.renderElement;
  14301. var staticBatchElementList = element.staticBatchElementList;
  14302. var batchElementList = staticBatchElementList.elements;
  14303. var from = 0;
  14304. var end = 0;
  14305. var count = staticBatchElementList.length;
  14306. for (var i = 1; i < count; i++) {
  14307. var lastElement = batchElementList[i - 1];
  14308. if (lastElement.staticBatchIndexEnd === batchElementList[i].staticBatchIndexStart) {
  14309. end++;
  14310. continue;
  14311. }
  14312. else {
  14313. var start = batchElementList[from].staticBatchIndexStart;
  14314. var indexCount = batchElementList[end].staticBatchIndexEnd - start;
  14315. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, start * 2);
  14316. from = ++end;
  14317. Laya.Stat.trianglesFaces += indexCount / 3;
  14318. }
  14319. }
  14320. start = batchElementList[from].staticBatchIndexStart;
  14321. indexCount = batchElementList[end].staticBatchIndexEnd - start;
  14322. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, start * 2);
  14323. Laya.Stat.renderBatches++;
  14324. Laya.Stat.savedRenderBatches += count - 1;
  14325. Laya.Stat.trianglesFaces += indexCount / 3;
  14326. }
  14327. dispose() {
  14328. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  14329. Laya.Resource._addGPUMemory(-memorySize);
  14330. this._batchElements = null;
  14331. this.batchOwner = null;
  14332. this._vertexDeclaration = null;
  14333. this._bufferState.destroy();
  14334. this._vertexBuffer.destroy();
  14335. this._indexBuffer.destroy();
  14336. this._vertexBuffer = null;
  14337. this._indexBuffer = null;
  14338. this._bufferState = null;
  14339. }
  14340. }
  14341. SubMeshStaticBatch._tempVector30 = new Vector3();
  14342. SubMeshStaticBatch._tempVector31 = new Vector3();
  14343. SubMeshStaticBatch._tempQuaternion0 = new Quaternion();
  14344. SubMeshStaticBatch._tempMatrix4x40 = new Matrix4x4();
  14345. SubMeshStaticBatch._tempMatrix4x41 = new Matrix4x4();
  14346. SubMeshStaticBatch.maxBatchVertexCount = 65535;
  14347. SubMeshStaticBatch._batchIDCounter = 0;
  14348. class SingletonList {
  14349. constructor() {
  14350. this.elements = [];
  14351. this.length = 0;
  14352. }
  14353. _add(element) {
  14354. if (this.length === this.elements.length)
  14355. this.elements.push(element);
  14356. else
  14357. this.elements[this.length] = element;
  14358. }
  14359. add(element) {
  14360. if (this.length === this.elements.length)
  14361. this.elements.push(element);
  14362. else
  14363. this.elements[this.length] = element;
  14364. this.length++;
  14365. }
  14366. }
  14367. class MeshRenderStaticBatchManager extends StaticBatchManager {
  14368. constructor() {
  14369. super();
  14370. this._opaqueBatchMarks = [];
  14371. this._updateCountMark = 0;
  14372. }
  14373. static __init__() {
  14374. MeshRenderStaticBatchManager._verDec = VertexMesh.getVertexDeclaration("POSITION,NORMAL,COLOR,UV,UV1,TANGENT");
  14375. }
  14376. _compare(left, right) {
  14377. var lRender = left._render, rRender = right._render;
  14378. var leftGeo = left.meshFilter.sharedMesh, rightGeo = right.meshFilter.sharedMesh;
  14379. var lightOffset = lRender.lightmapIndex - rRender.lightmapIndex;
  14380. if (lightOffset === 0) {
  14381. var receiveShadowOffset = (lRender.receiveShadow ? 1 : 0) - (rRender.receiveShadow ? 1 : 0);
  14382. if (receiveShadowOffset === 0) {
  14383. var materialOffset = (lRender.sharedMaterial && rRender.sharedMaterial) ? lRender.sharedMaterial.id - rRender.sharedMaterial.id : 0;
  14384. if (materialOffset === 0) {
  14385. var verDec = leftGeo._vertexBuffer.vertexDeclaration.id - rightGeo._vertexBuffer.vertexDeclaration.id;
  14386. if (verDec === 0) {
  14387. return rightGeo._indexBuffer.indexCount - leftGeo._indexBuffer.indexCount;
  14388. }
  14389. else {
  14390. return verDec;
  14391. }
  14392. }
  14393. else {
  14394. return materialOffset;
  14395. }
  14396. }
  14397. else {
  14398. return receiveShadowOffset;
  14399. }
  14400. }
  14401. else {
  14402. return lightOffset;
  14403. }
  14404. }
  14405. _getBatchRenderElementFromPool() {
  14406. var renderElement = this._batchRenderElementPool[this._batchRenderElementPoolIndex++];
  14407. if (!renderElement) {
  14408. renderElement = new SubMeshRenderElement();
  14409. this._batchRenderElementPool[this._batchRenderElementPoolIndex - 1] = renderElement;
  14410. renderElement.staticBatchElementList = new SingletonList();
  14411. }
  14412. return renderElement;
  14413. }
  14414. _getStaticBatch(staticBatches, rootOwner, number) {
  14415. var subMeshStaticBatch = staticBatches[number];
  14416. if (!subMeshStaticBatch) {
  14417. subMeshStaticBatch = staticBatches[number] = new SubMeshStaticBatch(rootOwner, MeshRenderStaticBatchManager._verDec);
  14418. this._staticBatches[subMeshStaticBatch._batchID] = subMeshStaticBatch;
  14419. }
  14420. return subMeshStaticBatch;
  14421. }
  14422. _initStaticBatchs(rootOwner) {
  14423. var initBatchSprites = this._initBatchSprites;
  14424. this._quickSort(initBatchSprites, 0, initBatchSprites.length - 1);
  14425. var staticBatches = [];
  14426. var lastCanMerage = false;
  14427. var curStaticBatch;
  14428. var batchNumber = 0;
  14429. for (var i = 0, n = initBatchSprites.length; i < n; i++) {
  14430. var sprite = initBatchSprites[i];
  14431. if (lastCanMerage) {
  14432. if (curStaticBatch.addTest(sprite)) {
  14433. curStaticBatch.add(sprite);
  14434. }
  14435. else {
  14436. lastCanMerage = false;
  14437. batchNumber++;
  14438. }
  14439. }
  14440. else {
  14441. var lastIndex = n - 1;
  14442. if (i !== lastIndex) {
  14443. curStaticBatch = this._getStaticBatch(staticBatches, rootOwner, batchNumber);
  14444. curStaticBatch.add(sprite);
  14445. lastCanMerage = true;
  14446. }
  14447. }
  14448. }
  14449. for (i = 0, n = staticBatches.length; i < n; i++) {
  14450. var staticBatch = staticBatches[i];
  14451. staticBatch && staticBatch.finishInit();
  14452. }
  14453. this._initBatchSprites.length = 0;
  14454. }
  14455. _removeRenderSprite(sprite) {
  14456. var render = sprite._render;
  14457. var staticBatch = render._staticBatch;
  14458. var batchElements = staticBatch._batchElements;
  14459. var index = batchElements.indexOf(sprite);
  14460. if (index !== -1) {
  14461. batchElements.splice(index, 1);
  14462. render._staticBatch = null;
  14463. var renderElements = render._renderElements;
  14464. for (var i = 0, n = renderElements.length; i < n; i++)
  14465. renderElements[i].staticBatch = null;
  14466. }
  14467. if (batchElements.length === 0) {
  14468. delete this._staticBatches[staticBatch._batchID];
  14469. staticBatch.dispose();
  14470. }
  14471. }
  14472. _clear() {
  14473. super._clear();
  14474. this._updateCountMark++;
  14475. }
  14476. _garbageCollection() {
  14477. for (var key in this._staticBatches) {
  14478. var staticBatch = this._staticBatches[key];
  14479. if (staticBatch._batchElements.length === 0) {
  14480. staticBatch.dispose();
  14481. delete this._staticBatches[key];
  14482. }
  14483. }
  14484. }
  14485. getBatchOpaquaMark(lightMapIndex, receiveShadow, materialID, staticBatchID) {
  14486. var receiveShadowIndex = receiveShadow ? 1 : 0;
  14487. var staLightMapMarks = (this._opaqueBatchMarks[lightMapIndex]) || (this._opaqueBatchMarks[lightMapIndex] = []);
  14488. var staReceiveShadowMarks = (staLightMapMarks[receiveShadowIndex]) || (staLightMapMarks[receiveShadowIndex] = []);
  14489. var staMaterialMarks = (staReceiveShadowMarks[materialID]) || (staReceiveShadowMarks[materialID] = []);
  14490. return (staMaterialMarks[staticBatchID]) || (staMaterialMarks[staticBatchID] = new BatchMark);
  14491. }
  14492. }
  14493. MeshRenderStaticBatchManager.instance = new MeshRenderStaticBatchManager();
  14494. class MeshSprite3DShaderDeclaration {
  14495. }
  14496. class BoundBox {
  14497. constructor(min, max) {
  14498. this.min = min;
  14499. this.max = max;
  14500. }
  14501. _rotateExtents(extents, rotation, out) {
  14502. var extentsX = extents.x;
  14503. var extentsY = extents.y;
  14504. var extentsZ = extents.z;
  14505. var matElements = rotation.elements;
  14506. out.x = Math.abs(matElements[0] * extentsX) + Math.abs(matElements[4] * extentsY) + Math.abs(matElements[8] * extentsZ);
  14507. out.y = Math.abs(matElements[1] * extentsX) + Math.abs(matElements[5] * extentsY) + Math.abs(matElements[9] * extentsZ);
  14508. out.z = Math.abs(matElements[2] * extentsX) + Math.abs(matElements[6] * extentsY) + Math.abs(matElements[10] * extentsZ);
  14509. }
  14510. getCorners(corners) {
  14511. corners.length = 8;
  14512. var minX = this.min.x;
  14513. var minY = this.min.y;
  14514. var minZ = this.min.z;
  14515. var maxX = this.max.x;
  14516. var maxY = this.max.y;
  14517. var maxZ = this.max.z;
  14518. corners[0] = new Vector3(minX, maxY, maxZ);
  14519. corners[1] = new Vector3(maxX, maxY, maxZ);
  14520. corners[2] = new Vector3(maxX, minY, maxZ);
  14521. corners[3] = new Vector3(minX, minY, maxZ);
  14522. corners[4] = new Vector3(minX, maxY, minZ);
  14523. corners[5] = new Vector3(maxX, maxY, minZ);
  14524. corners[6] = new Vector3(maxX, minY, minZ);
  14525. corners[7] = new Vector3(minX, minY, minZ);
  14526. }
  14527. getCenter(out) {
  14528. Vector3.add(this.min, this.max, out);
  14529. Vector3.scale(out, 0.5, out);
  14530. }
  14531. getExtent(out) {
  14532. Vector3.subtract(this.max, this.min, out);
  14533. Vector3.scale(out, 0.5, out);
  14534. }
  14535. setCenterAndExtent(center, extent) {
  14536. Vector3.subtract(center, extent, this.min);
  14537. Vector3.add(center, extent, this.max);
  14538. }
  14539. tranform(matrix, out) {
  14540. var center = BoundBox._tempVector30;
  14541. var extent = BoundBox._tempVector31;
  14542. this.getCenter(center);
  14543. this.getExtent(extent);
  14544. Vector3.transformCoordinate(center, matrix, center);
  14545. this._rotateExtents(extent, matrix, extent);
  14546. out.setCenterAndExtent(center, extent);
  14547. }
  14548. toDefault() {
  14549. this.min.toDefault();
  14550. this.max.toDefault();
  14551. }
  14552. static createfromPoints(points, out) {
  14553. if (points == null)
  14554. throw new Error("points");
  14555. var min = out.min;
  14556. var max = out.max;
  14557. min.x = Number.MAX_VALUE;
  14558. min.y = Number.MAX_VALUE;
  14559. min.z = Number.MAX_VALUE;
  14560. max.x = -Number.MAX_VALUE;
  14561. max.y = -Number.MAX_VALUE;
  14562. max.z = -Number.MAX_VALUE;
  14563. for (var i = 0, n = points.length; i < n; ++i) {
  14564. Vector3.min(min, points[i], min);
  14565. Vector3.max(max, points[i], max);
  14566. }
  14567. }
  14568. static merge(box1, box2, out) {
  14569. Vector3.min(box1.min, box2.min, out.min);
  14570. Vector3.max(box1.max, box2.max, out.max);
  14571. }
  14572. cloneTo(destObject) {
  14573. var dest = destObject;
  14574. this.min.cloneTo(dest.min);
  14575. this.max.cloneTo(dest.max);
  14576. }
  14577. clone() {
  14578. var dest = new BoundBox(new Vector3(), new Vector3());
  14579. this.cloneTo(dest);
  14580. return dest;
  14581. }
  14582. }
  14583. BoundBox._tempVector30 = new Vector3();
  14584. BoundBox._tempVector31 = new Vector3();
  14585. class Bounds {
  14586. constructor(min, max) {
  14587. this._updateFlag = 0;
  14588. this._center = new Vector3();
  14589. this._extent = new Vector3();
  14590. this._boundBox = new BoundBox(new Vector3(), new Vector3());
  14591. min.cloneTo(this._boundBox.min);
  14592. max.cloneTo(this._boundBox.max);
  14593. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  14594. }
  14595. setMin(value) {
  14596. var min = this._boundBox.min;
  14597. if (value !== min)
  14598. value.cloneTo(min);
  14599. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  14600. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  14601. }
  14602. getMin() {
  14603. var min = this._boundBox.min;
  14604. if (this._getUpdateFlag(Bounds._UPDATE_MIN)) {
  14605. this._getMin(this.getCenter(), this.getExtent(), min);
  14606. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  14607. }
  14608. return min;
  14609. }
  14610. setMax(value) {
  14611. var max = this._boundBox.max;
  14612. if (value !== max)
  14613. value.cloneTo(max);
  14614. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  14615. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  14616. }
  14617. getMax() {
  14618. var max = this._boundBox.max;
  14619. if (this._getUpdateFlag(Bounds._UPDATE_MAX)) {
  14620. this._getMax(this.getCenter(), this.getExtent(), max);
  14621. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  14622. }
  14623. return max;
  14624. }
  14625. setCenter(value) {
  14626. if (value !== this._center)
  14627. value.cloneTo(this._center);
  14628. this._setUpdateFlag(Bounds._UPDATE_MIN | Bounds._UPDATE_MAX, true);
  14629. this._setUpdateFlag(Bounds._UPDATE_CENTER, false);
  14630. }
  14631. getCenter() {
  14632. if (this._getUpdateFlag(Bounds._UPDATE_CENTER)) {
  14633. this._getCenter(this.getMin(), this.getMax(), this._center);
  14634. this._setUpdateFlag(Bounds._UPDATE_CENTER, false);
  14635. }
  14636. return this._center;
  14637. }
  14638. setExtent(value) {
  14639. if (value !== this._extent)
  14640. value.cloneTo(this._extent);
  14641. this._setUpdateFlag(Bounds._UPDATE_MIN | Bounds._UPDATE_MAX, true);
  14642. this._setUpdateFlag(Bounds._UPDATE_EXTENT, false);
  14643. }
  14644. getExtent() {
  14645. if (this._getUpdateFlag(Bounds._UPDATE_EXTENT)) {
  14646. this._getExtent(this.getMin(), this.getMax(), this._extent);
  14647. this._setUpdateFlag(Bounds._UPDATE_EXTENT, false);
  14648. }
  14649. return this._extent;
  14650. }
  14651. _getUpdateFlag(type) {
  14652. return (this._updateFlag & type) != 0;
  14653. }
  14654. _setUpdateFlag(type, value) {
  14655. if (value)
  14656. this._updateFlag |= type;
  14657. else
  14658. this._updateFlag &= ~type;
  14659. }
  14660. _getCenter(min, max, out) {
  14661. Vector3.add(min, max, out);
  14662. Vector3.scale(out, 0.5, out);
  14663. }
  14664. _getExtent(min, max, out) {
  14665. Vector3.subtract(max, min, out);
  14666. Vector3.scale(out, 0.5, out);
  14667. }
  14668. _getMin(center, extent, out) {
  14669. Vector3.subtract(center, extent, out);
  14670. }
  14671. _getMax(center, extent, out) {
  14672. Vector3.add(center, extent, out);
  14673. }
  14674. _rotateExtents(extents, rotation, out) {
  14675. var extentsX = extents.x;
  14676. var extentsY = extents.y;
  14677. var extentsZ = extents.z;
  14678. var matE = rotation.elements;
  14679. out.x = Math.abs(matE[0] * extentsX) + Math.abs(matE[4] * extentsY) + Math.abs(matE[8] * extentsZ);
  14680. out.y = Math.abs(matE[1] * extentsX) + Math.abs(matE[5] * extentsY) + Math.abs(matE[9] * extentsZ);
  14681. out.z = Math.abs(matE[2] * extentsX) + Math.abs(matE[6] * extentsY) + Math.abs(matE[10] * extentsZ);
  14682. }
  14683. _tranform(matrix, out) {
  14684. var outCen = out._center;
  14685. var outExt = out._extent;
  14686. Vector3.transformCoordinate(this.getCenter(), matrix, outCen);
  14687. this._rotateExtents(this.getExtent(), matrix, outExt);
  14688. out._boundBox.setCenterAndExtent(outCen, outExt);
  14689. out._updateFlag = 0;
  14690. }
  14691. _getBoundBox() {
  14692. if (this._updateFlag & Bounds._UPDATE_MIN) {
  14693. var min = this._boundBox.min;
  14694. this._getMin(this.getCenter(), this.getExtent(), min);
  14695. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  14696. }
  14697. if (this._updateFlag & Bounds._UPDATE_MAX) {
  14698. var max = this._boundBox.max;
  14699. this._getMax(this.getCenter(), this.getExtent(), max);
  14700. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  14701. }
  14702. return this._boundBox;
  14703. }
  14704. cloneTo(destObject) {
  14705. var destBounds = destObject;
  14706. this.getMin().cloneTo(destBounds._boundBox.min);
  14707. this.getMax().cloneTo(destBounds._boundBox.max);
  14708. this.getCenter().cloneTo(destBounds._center);
  14709. this.getExtent().cloneTo(destBounds._extent);
  14710. destBounds._updateFlag = 0;
  14711. }
  14712. clone() {
  14713. var dest = new Bounds(new Vector3(), new Vector3());
  14714. this.cloneTo(dest);
  14715. return dest;
  14716. }
  14717. }
  14718. Bounds._UPDATE_MIN = 0x01;
  14719. Bounds._UPDATE_MAX = 0x02;
  14720. Bounds._UPDATE_CENTER = 0x04;
  14721. Bounds._UPDATE_EXTENT = 0x08;
  14722. class BaseRender extends Laya.EventDispatcher {
  14723. constructor(owner) {
  14724. super();
  14725. this._indexInList = -1;
  14726. this._indexInCastShadowList = -1;
  14727. this._boundsChange = true;
  14728. this._supportOctree = true;
  14729. this._sharedMaterials = [];
  14730. this._visible = true;
  14731. this._indexInOctreeMotionList = -1;
  14732. this._updateMark = -1;
  14733. this._updateRenderType = -1;
  14734. this._isPartOfStaticBatch = false;
  14735. this._staticBatch = null;
  14736. this._id = ++BaseRender._uniqueIDCounter;
  14737. this._indexInCastShadowList = -1;
  14738. this._bounds = new Bounds(Vector3._ZERO, Vector3._ZERO);
  14739. if (Laya.Render.supportWebGLPlusCulling) {
  14740. var length = FrustumCulling._cullingBufferLength;
  14741. this._cullingBufferIndex = length;
  14742. var cullingBuffer = FrustumCulling._cullingBuffer;
  14743. var resizeLength = length + 7;
  14744. if (resizeLength >= cullingBuffer.length) {
  14745. var temp = cullingBuffer;
  14746. cullingBuffer = FrustumCulling._cullingBuffer = new Float32Array(cullingBuffer.length + 4096);
  14747. cullingBuffer.set(temp, 0);
  14748. }
  14749. cullingBuffer[length] = 2;
  14750. FrustumCulling._cullingBufferLength = resizeLength;
  14751. }
  14752. this._renderElements = [];
  14753. this._owner = owner;
  14754. this._enable = true;
  14755. this._materialsInstance = [];
  14756. this._shaderValues = new ShaderData(null);
  14757. this.lightmapIndex = -1;
  14758. this._castShadow = false;
  14759. this.receiveShadow = false;
  14760. this.sortingFudge = 0.0;
  14761. (owner) && (this._owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  14762. }
  14763. get id() {
  14764. return this._id;
  14765. }
  14766. get lightmapIndex() {
  14767. return this._lightmapIndex;
  14768. }
  14769. set lightmapIndex(value) {
  14770. if (this._lightmapIndex !== value) {
  14771. this._lightmapIndex = value;
  14772. this._applyLightMapParams();
  14773. }
  14774. }
  14775. get lightmapScaleOffset() {
  14776. return this._lightmapScaleOffset;
  14777. }
  14778. set lightmapScaleOffset(value) {
  14779. this._lightmapScaleOffset = value;
  14780. this._shaderValues.setVector(RenderableSprite3D.LIGHTMAPSCALEOFFSET, value);
  14781. this._shaderValues.addDefine(RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV);
  14782. }
  14783. get enable() {
  14784. return this._enable;
  14785. }
  14786. set enable(value) {
  14787. this._enable = !!value;
  14788. }
  14789. get material() {
  14790. var material = this._sharedMaterials[0];
  14791. if (material && !this._materialsInstance[0]) {
  14792. var insMat = this._getInstanceMaterial(material, 0);
  14793. var renderElement = this._renderElements[0];
  14794. (renderElement) && (renderElement.material = insMat);
  14795. }
  14796. return this._sharedMaterials[0];
  14797. }
  14798. set material(value) {
  14799. this.sharedMaterial = value;
  14800. }
  14801. get materials() {
  14802. for (var i = 0, n = this._sharedMaterials.length; i < n; i++) {
  14803. if (!this._materialsInstance[i]) {
  14804. var insMat = this._getInstanceMaterial(this._sharedMaterials[i], i);
  14805. var renderElement = this._renderElements[i];
  14806. (renderElement) && (renderElement.material = insMat);
  14807. }
  14808. }
  14809. return this._sharedMaterials.slice();
  14810. }
  14811. set materials(value) {
  14812. this.sharedMaterials = value;
  14813. }
  14814. get sharedMaterial() {
  14815. return this._sharedMaterials[0];
  14816. }
  14817. set sharedMaterial(value) {
  14818. var lastValue = this._sharedMaterials[0];
  14819. if (lastValue !== value) {
  14820. this._sharedMaterials[0] = value;
  14821. this._materialsInstance[0] = false;
  14822. this._changeMaterialReference(lastValue, value);
  14823. var renderElement = this._renderElements[0];
  14824. (renderElement) && (renderElement.material = value);
  14825. }
  14826. }
  14827. get sharedMaterials() {
  14828. return this._sharedMaterials.slice();
  14829. }
  14830. set sharedMaterials(value) {
  14831. var materialsInstance = this._materialsInstance;
  14832. var sharedMats = this._sharedMaterials;
  14833. for (var i = 0, n = sharedMats.length; i < n; i++) {
  14834. var lastMat = sharedMats[i];
  14835. (lastMat) && (lastMat._removeReference());
  14836. }
  14837. if (value) {
  14838. var count = value.length;
  14839. materialsInstance.length = count;
  14840. sharedMats.length = count;
  14841. for (i = 0; i < count; i++) {
  14842. lastMat = sharedMats[i];
  14843. var mat = value[i];
  14844. if (lastMat !== mat) {
  14845. materialsInstance[i] = false;
  14846. var renderElement = this._renderElements[i];
  14847. (renderElement) && (renderElement.material = mat);
  14848. }
  14849. if (mat) {
  14850. mat._addReference();
  14851. }
  14852. sharedMats[i] = mat;
  14853. }
  14854. }
  14855. else {
  14856. throw new Error("BaseRender: shadredMaterials value can't be null.");
  14857. }
  14858. }
  14859. get bounds() {
  14860. if (this._boundsChange) {
  14861. this._calculateBoundingBox();
  14862. this._boundsChange = false;
  14863. }
  14864. return this._bounds;
  14865. }
  14866. set receiveShadow(value) {
  14867. if (this._receiveShadow !== value) {
  14868. this._receiveShadow = value;
  14869. if (value)
  14870. this._shaderValues.addDefine(RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW);
  14871. else
  14872. this._shaderValues.removeDefine(RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW);
  14873. }
  14874. }
  14875. get receiveShadow() {
  14876. return this._receiveShadow;
  14877. }
  14878. get castShadow() {
  14879. return this._castShadow;
  14880. }
  14881. set castShadow(value) {
  14882. if (this._castShadow !== value) {
  14883. if (this._owner.activeInHierarchy) {
  14884. if (value)
  14885. this._scene._addShadowCastRenderObject(this);
  14886. else
  14887. this._scene._removeShadowCastRenderObject(this);
  14888. }
  14889. this._castShadow = value;
  14890. }
  14891. }
  14892. get isPartOfStaticBatch() {
  14893. return this._isPartOfStaticBatch;
  14894. }
  14895. _getOctreeNode() {
  14896. return this._octreeNode;
  14897. }
  14898. _setOctreeNode(value) {
  14899. this._octreeNode = value;
  14900. }
  14901. _getIndexInMotionList() {
  14902. return this._indexInOctreeMotionList;
  14903. }
  14904. _setIndexInMotionList(value) {
  14905. this._indexInOctreeMotionList = value;
  14906. }
  14907. _changeMaterialReference(lastValue, value) {
  14908. (lastValue) && (lastValue._removeReference());
  14909. value._addReference();
  14910. }
  14911. _getInstanceMaterial(material, index) {
  14912. var insMat = material.clone();
  14913. insMat.name = insMat.name + "(Instance)";
  14914. this._materialsInstance[index] = true;
  14915. this._changeMaterialReference(this._sharedMaterials[index], insMat);
  14916. this._sharedMaterials[index] = insMat;
  14917. return insMat;
  14918. }
  14919. _applyLightMapParams() {
  14920. if (this._scene && this._lightmapIndex >= 0) {
  14921. var lightMaps = this._scene.getlightmaps();
  14922. if (this._lightmapIndex < lightMaps.length) {
  14923. this._shaderValues.addDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  14924. this._shaderValues.setTexture(RenderableSprite3D.LIGHTMAP, lightMaps[this._lightmapIndex]);
  14925. }
  14926. else {
  14927. this._shaderValues.removeDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  14928. }
  14929. }
  14930. else {
  14931. this._shaderValues.removeDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  14932. }
  14933. }
  14934. _onWorldMatNeedChange(flag) {
  14935. this._boundsChange = true;
  14936. if (this._octreeNode) {
  14937. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  14938. if (flag) {
  14939. if (this._indexInOctreeMotionList === -1)
  14940. this._octreeNode._octree.addMotionObject(this);
  14941. }
  14942. }
  14943. }
  14944. _calculateBoundingBox() {
  14945. throw ("BaseRender: must override it.");
  14946. }
  14947. _getIndexInList() {
  14948. return this._indexInList;
  14949. }
  14950. _setIndexInList(index) {
  14951. this._indexInList = index;
  14952. }
  14953. _setBelongScene(scene) {
  14954. if (this._scene !== scene) {
  14955. this._scene = scene;
  14956. this._applyLightMapParams();
  14957. }
  14958. }
  14959. _needRender(boundFrustum, context) {
  14960. return true;
  14961. }
  14962. _renderUpdate(context, transform) {
  14963. }
  14964. _renderUpdateWithCamera(context, transform) {
  14965. }
  14966. _revertBatchRenderUpdate(context) {
  14967. }
  14968. _destroy() {
  14969. (this._indexInOctreeMotionList !== -1) && (this._octreeNode._octree.removeMotionObject(this));
  14970. this.offAll();
  14971. var i = 0, n = 0;
  14972. for (i = 0, n = this._renderElements.length; i < n; i++)
  14973. this._renderElements[i].destroy();
  14974. for (i = 0, n = this._sharedMaterials.length; i < n; i++)
  14975. (this._sharedMaterials[i].destroyed) || (this._sharedMaterials[i]._removeReference());
  14976. this._renderElements = null;
  14977. this._owner = null;
  14978. this._sharedMaterials = null;
  14979. this._bounds = null;
  14980. this._lightmapScaleOffset = null;
  14981. }
  14982. markAsUnStatic() {
  14983. if (this._isPartOfStaticBatch) {
  14984. MeshRenderStaticBatchManager.instance._removeRenderSprite(this._owner);
  14985. this._isPartOfStaticBatch = false;
  14986. }
  14987. }
  14988. }
  14989. BaseRender._tempBoundBoxCorners = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  14990. BaseRender._uniqueIDCounter = 0;
  14991. class MeshRenderer extends BaseRender {
  14992. constructor(owner) {
  14993. super(owner);
  14994. this._revertStaticBatchDefineUV1 = false;
  14995. this._revertStaticBatchDefineLightMapUV = false;
  14996. this._projectionViewWorldMatrix = new Matrix4x4();
  14997. }
  14998. _createRenderElement() {
  14999. return new SubMeshRenderElement();
  15000. }
  15001. _onMeshChange(mesh) {
  15002. if (mesh) {
  15003. var count = mesh.subMeshCount;
  15004. this._renderElements.length = count;
  15005. for (var i = 0; i < count; i++) {
  15006. var renderElement = this._renderElements[i];
  15007. if (!renderElement) {
  15008. var material = this.sharedMaterials[i];
  15009. renderElement = this._renderElements[i] = this._createRenderElement();
  15010. renderElement.setTransform(this._owner._transform);
  15011. renderElement.render = this;
  15012. renderElement.material = material ? material : BlinnPhongMaterial.defaultMaterial;
  15013. }
  15014. renderElement.setGeometry(mesh.getSubMesh(i));
  15015. }
  15016. }
  15017. else {
  15018. this._renderElements.length = 0;
  15019. }
  15020. this._boundsChange = true;
  15021. }
  15022. _calculateBoundingBox() {
  15023. var sharedMesh = this._owner.meshFilter.sharedMesh;
  15024. if (sharedMesh) {
  15025. var worldMat = this._owner.transform.worldMatrix;
  15026. sharedMesh.bounds._tranform(worldMat, this._bounds);
  15027. }
  15028. if (Laya.Render.supportWebGLPlusCulling) {
  15029. var min = this._bounds.getMin();
  15030. var max = this._bounds.getMax();
  15031. var buffer = FrustumCulling._cullingBuffer;
  15032. buffer[this._cullingBufferIndex + 1] = min.x;
  15033. buffer[this._cullingBufferIndex + 2] = min.y;
  15034. buffer[this._cullingBufferIndex + 3] = min.z;
  15035. buffer[this._cullingBufferIndex + 4] = max.x;
  15036. buffer[this._cullingBufferIndex + 5] = max.y;
  15037. buffer[this._cullingBufferIndex + 6] = max.z;
  15038. }
  15039. }
  15040. _needRender(boundFrustum, context) {
  15041. if (boundFrustum)
  15042. return boundFrustum.intersects(this.bounds._getBoundBox());
  15043. else
  15044. return true;
  15045. }
  15046. _renderUpdate(context, transform) {
  15047. var element = context.renderElement;
  15048. switch (element.renderType) {
  15049. case RenderElement.RENDERTYPE_NORMAL:
  15050. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  15051. break;
  15052. case RenderElement.RENDERTYPE_STATICBATCH:
  15053. if (transform)
  15054. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  15055. else
  15056. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  15057. if (!this._shaderValues.hasDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1)) {
  15058. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  15059. this._revertStaticBatchDefineUV1 = true;
  15060. }
  15061. else {
  15062. this._revertStaticBatchDefineUV1 = false;
  15063. }
  15064. if (this._shaderValues.hasDefine(RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV)) {
  15065. this._shaderValues.removeDefine(RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV);
  15066. this._revertStaticBatchDefineLightMapUV = true;
  15067. }
  15068. else {
  15069. this._revertStaticBatchDefineLightMapUV = false;
  15070. }
  15071. break;
  15072. case RenderElement.RENDERTYPE_VERTEXBATCH:
  15073. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  15074. break;
  15075. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  15076. var worldMatrixData = SubMeshInstanceBatch.instance.instanceWorldMatrixData;
  15077. var insBatches = element.instanceBatchElementList;
  15078. var elements = insBatches.elements;
  15079. var count = insBatches.length;
  15080. for (var i = 0; i < count; i++)
  15081. worldMatrixData.set(elements[i]._transform.worldMatrix.elements, i * 16);
  15082. SubMeshInstanceBatch.instance.instanceWorldMatrixBuffer.setData(worldMatrixData.buffer, 0, 0, count * 16 * 4);
  15083. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE);
  15084. break;
  15085. }
  15086. }
  15087. _renderUpdateWithCamera(context, transform) {
  15088. var projectionView = context.projectionViewMatrix;
  15089. var element = context.renderElement;
  15090. switch (element.renderType) {
  15091. case RenderElement.RENDERTYPE_NORMAL:
  15092. case RenderElement.RENDERTYPE_STATICBATCH:
  15093. case RenderElement.RENDERTYPE_VERTEXBATCH:
  15094. if (transform) {
  15095. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  15096. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  15097. }
  15098. else {
  15099. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  15100. }
  15101. break;
  15102. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  15103. var mvpMatrixData = SubMeshInstanceBatch.instance.instanceMVPMatrixData;
  15104. var insBatches = element.instanceBatchElementList;
  15105. var elements = insBatches.elements;
  15106. var count = insBatches.length;
  15107. for (var i = 0; i < count; i++) {
  15108. var worldMat = elements[i]._transform.worldMatrix;
  15109. Utils3D.mulMatrixByArray(projectionView.elements, 0, worldMat.elements, 0, mvpMatrixData, i * 16);
  15110. }
  15111. SubMeshInstanceBatch.instance.instanceMVPMatrixBuffer.setData(mvpMatrixData.buffer, 0, 0, count * 16 * 4);
  15112. break;
  15113. }
  15114. }
  15115. _revertBatchRenderUpdate(context) {
  15116. var element = context.renderElement;
  15117. switch (element.renderType) {
  15118. case RenderElement.RENDERTYPE_STATICBATCH:
  15119. if (this._revertStaticBatchDefineUV1)
  15120. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  15121. if (this._revertStaticBatchDefineLightMapUV)
  15122. this._shaderValues.addDefine(RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV);
  15123. break;
  15124. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  15125. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE);
  15126. break;
  15127. }
  15128. }
  15129. _destroy() {
  15130. (this._isPartOfStaticBatch) && (MeshRenderStaticBatchManager.instance._removeRenderSprite(this._owner));
  15131. super._destroy();
  15132. }
  15133. }
  15134. class MeshFilter {
  15135. constructor(owner) {
  15136. this._owner = owner;
  15137. }
  15138. get sharedMesh() {
  15139. return this._sharedMesh;
  15140. }
  15141. set sharedMesh(value) {
  15142. if (this._sharedMesh !== value) {
  15143. var defineDatas = this._owner._render._shaderValues;
  15144. var lastValue = this._sharedMesh;
  15145. if (lastValue) {
  15146. lastValue._removeReference();
  15147. this._getMeshDefine(lastValue, MeshFilter._meshVerticeDefine);
  15148. for (var i = 0, n = MeshFilter._meshVerticeDefine.length; i < n; i++)
  15149. defineDatas.removeDefine(MeshFilter._meshVerticeDefine[i]);
  15150. }
  15151. if (value) {
  15152. value._addReference();
  15153. this._getMeshDefine(value, MeshFilter._meshVerticeDefine);
  15154. for (var i = 0, n = MeshFilter._meshVerticeDefine.length; i < n; i++)
  15155. defineDatas.addDefine(MeshFilter._meshVerticeDefine[i]);
  15156. }
  15157. this._owner._render._onMeshChange(value);
  15158. this._sharedMesh = value;
  15159. }
  15160. }
  15161. _getMeshDefine(mesh, out) {
  15162. out.length = 0;
  15163. var define;
  15164. for (var i = 0, n = mesh._subMeshes.length; i < n; i++) {
  15165. var subMesh = mesh.getSubMesh(i);
  15166. var vertexElements = subMesh._vertexBuffer._vertexDeclaration._vertexElements;
  15167. for (var j = 0, m = vertexElements.length; j < m; j++) {
  15168. var vertexElement = vertexElements[j];
  15169. var name = vertexElement._elementUsage;
  15170. switch (name) {
  15171. case VertexMesh.MESH_COLOR0:
  15172. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_COLOR);
  15173. break;
  15174. case VertexMesh.MESH_TEXTURECOORDINATE0:
  15175. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV0);
  15176. break;
  15177. case VertexMesh.MESH_TEXTURECOORDINATE1:
  15178. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  15179. break;
  15180. }
  15181. }
  15182. }
  15183. return define;
  15184. }
  15185. destroy() {
  15186. this._owner = null;
  15187. (this._sharedMesh) && (this._sharedMesh._removeReference(), this._sharedMesh = null);
  15188. }
  15189. }
  15190. MeshFilter._meshVerticeDefine = [];
  15191. class SubMeshDynamicBatch extends GeometryElement {
  15192. constructor() {
  15193. super();
  15194. this._bufferState = new BufferState();
  15195. var gl = Laya.LayaGL.instance;
  15196. var maxVerDec = VertexMesh.getVertexDeclaration("POSITION,NORMAL,COLOR,UV,UV1,TANGENT");
  15197. var maxByteCount = maxVerDec.vertexStride * SubMeshDynamicBatch.maxIndicesCount;
  15198. this._vertices = new Float32Array(maxByteCount / 4);
  15199. this._vertexBuffer = new VertexBuffer3D(maxByteCount, gl.DYNAMIC_DRAW);
  15200. this._indices = new Int16Array(SubMeshDynamicBatch.maxIndicesCount);
  15201. this._indexBuffer = new IndexBuffer3D(IndexBuffer3D.INDEXTYPE_USHORT, this._indices.length, gl.DYNAMIC_DRAW);
  15202. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  15203. Laya.Resource._addMemory(memorySize, memorySize);
  15204. }
  15205. static __init__() {
  15206. SubMeshDynamicBatch.instance = new SubMeshDynamicBatch();
  15207. }
  15208. _getBatchVertices(vertexDeclaration, batchVertices, batchOffset, transform, element, subMesh) {
  15209. var vertexFloatCount = vertexDeclaration.vertexStride / 4;
  15210. var oriVertexes = subMesh._vertexBuffer.getFloat32Data();
  15211. var lightmapScaleOffset = element.render.lightmapScaleOffset;
  15212. var multiSubMesh = element._dynamicMultiSubMesh;
  15213. var vertexCount = element._dynamicVertexCount;
  15214. element._computeWorldPositionsAndNormals(this._positionOffset, this._normalOffset, multiSubMesh, vertexCount);
  15215. var worldPositions = element._dynamicWorldPositions;
  15216. var worldNormals = element._dynamicWorldNormals;
  15217. var indices = subMesh._indices;
  15218. for (var i = 0; i < vertexCount; i++) {
  15219. var index = multiSubMesh ? indices[i] : i;
  15220. var oriOffset = index * vertexFloatCount;
  15221. var bakeOffset = (i + batchOffset) * vertexFloatCount;
  15222. var oriOff = i * 3;
  15223. var bakOff = bakeOffset + this._positionOffset;
  15224. batchVertices[bakOff] = worldPositions[oriOff];
  15225. batchVertices[bakOff + 1] = worldPositions[oriOff + 1];
  15226. batchVertices[bakOff + 2] = worldPositions[oriOff + 2];
  15227. if (this._normalOffset !== -1) {
  15228. bakOff = bakeOffset + this._normalOffset;
  15229. batchVertices[bakOff] = worldNormals[oriOff];
  15230. batchVertices[bakOff + 1] = worldNormals[oriOff + 1];
  15231. batchVertices[bakOff + 2] = worldNormals[oriOff + 2];
  15232. }
  15233. if (this._colorOffset !== -1) {
  15234. bakOff = bakeOffset + this._colorOffset;
  15235. oriOff = oriOffset + this._colorOffset;
  15236. batchVertices[bakOff] = oriVertexes[oriOff];
  15237. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  15238. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  15239. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  15240. }
  15241. if (this._uv0Offset !== -1) {
  15242. bakOff = bakeOffset + this._uv0Offset;
  15243. oriOff = oriOffset + this._uv0Offset;
  15244. batchVertices[bakOff] = oriVertexes[oriOff];
  15245. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  15246. }
  15247. if (this._sTangentOffset !== -1) {
  15248. bakOff = bakeOffset + this._sTangentOffset;
  15249. oriOff = oriOffset + this._sTangentOffset;
  15250. batchVertices[bakOff] = oriVertexes[oriOff];
  15251. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  15252. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  15253. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  15254. bakOff = bakeOffset + this._sTangentOffset;
  15255. oriOff = oriOffset + this._sTangentOffset;
  15256. batchVertices[bakOff] = oriVertexes[oriOff];
  15257. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  15258. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  15259. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  15260. }
  15261. }
  15262. }
  15263. _getBatchIndices(batchIndices, batchIndexCount, batchVertexCount, transform, subMesh, multiSubMesh) {
  15264. var subIndices = subMesh._indices;
  15265. var k, m, batchOffset;
  15266. var isInvert = transform._isFrontFaceInvert;
  15267. if (multiSubMesh) {
  15268. if (isInvert) {
  15269. for (k = 0, m = subIndices.length; k < m; k += 3) {
  15270. batchOffset = batchIndexCount + k;
  15271. var index = batchVertexCount + k;
  15272. batchIndices[batchOffset] = index;
  15273. batchIndices[batchOffset + 1] = index + 2;
  15274. batchIndices[batchOffset + 2] = index + 1;
  15275. }
  15276. }
  15277. else {
  15278. for (k = 0, m = subIndices.length; k < m; k += 3) {
  15279. batchOffset = batchIndexCount + k;
  15280. index = batchVertexCount + k;
  15281. batchIndices[batchOffset] = index;
  15282. batchIndices[batchOffset + 1] = index + 1;
  15283. batchIndices[batchOffset + 2] = index + 2;
  15284. }
  15285. }
  15286. }
  15287. else {
  15288. if (isInvert) {
  15289. for (k = 0, m = subIndices.length; k < m; k += 3) {
  15290. batchOffset = batchIndexCount + k;
  15291. batchIndices[batchOffset] = batchVertexCount + subIndices[k];
  15292. batchIndices[batchOffset + 1] = batchVertexCount + subIndices[k + 2];
  15293. batchIndices[batchOffset + 2] = batchVertexCount + subIndices[k + 1];
  15294. }
  15295. }
  15296. else {
  15297. for (k = 0, m = subIndices.length; k < m; k += 3) {
  15298. batchOffset = batchIndexCount + k;
  15299. batchIndices[batchOffset] = batchVertexCount + subIndices[k];
  15300. batchIndices[batchOffset + 1] = batchVertexCount + subIndices[k + 1];
  15301. batchIndices[batchOffset + 2] = batchVertexCount + subIndices[k + 2];
  15302. }
  15303. }
  15304. }
  15305. }
  15306. _flush(vertexCount, indexCount) {
  15307. var gl = Laya.LayaGL.instance;
  15308. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, vertexCount * (this._bufferState.vertexDeclaration.vertexStride));
  15309. this._indexBuffer.setData(this._indices, 0, 0, indexCount);
  15310. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  15311. }
  15312. _prepareRender(state) {
  15313. var element = state.renderElement;
  15314. var vertexDeclaration = element.vertexBatchVertexDeclaration;
  15315. this._bufferState = ILaya3D.MeshRenderDynamicBatchManager.instance._getBufferState(vertexDeclaration);
  15316. this._positionOffset = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  15317. var normalElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_NORMAL0);
  15318. this._normalOffset = normalElement ? normalElement._offset / 4 : -1;
  15319. var colorElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  15320. this._colorOffset = colorElement ? colorElement._offset / 4 : -1;
  15321. var uv0Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  15322. this._uv0Offset = uv0Element ? uv0Element._offset / 4 : -1;
  15323. var uv1Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE1);
  15324. this._uv1Offset = uv1Element ? uv1Element._offset / 4 : -1;
  15325. var tangentElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TANGENT0);
  15326. this._sTangentOffset = tangentElement ? tangentElement._offset / 4 : -1;
  15327. return true;
  15328. }
  15329. _render(context) {
  15330. this._bufferState.bind();
  15331. var element = context.renderElement;
  15332. var vertexDeclaration = element.vertexBatchVertexDeclaration;
  15333. var batchElements = element.vertexBatchElementList;
  15334. var batchVertexCount = 0;
  15335. var batchIndexCount = 0;
  15336. var floatStride = vertexDeclaration.vertexStride / 4;
  15337. var renderBatchCount = 0;
  15338. var elementCount = batchElements.length;
  15339. var elements = batchElements.elements;
  15340. for (var i = 0; i < elementCount; i++) {
  15341. var subElement = elements[i];
  15342. var subMesh = subElement._geometry;
  15343. var indexCount = subMesh._indexCount;
  15344. if (batchIndexCount + indexCount > SubMeshDynamicBatch.maxIndicesCount) {
  15345. this._flush(batchVertexCount, batchIndexCount);
  15346. renderBatchCount++;
  15347. Laya.Stat.trianglesFaces += batchIndexCount / 3;
  15348. batchVertexCount = batchIndexCount = 0;
  15349. }
  15350. var transform = subElement._transform;
  15351. this._getBatchVertices(vertexDeclaration, this._vertices, batchVertexCount, transform, subElement, subMesh);
  15352. this._getBatchIndices(this._indices, batchIndexCount, batchVertexCount, transform, subMesh, subElement._dynamicMultiSubMesh);
  15353. batchVertexCount += subElement._dynamicVertexCount;
  15354. batchIndexCount += indexCount;
  15355. }
  15356. this._flush(batchVertexCount, batchIndexCount);
  15357. renderBatchCount++;
  15358. Laya.Stat.renderBatches += renderBatchCount;
  15359. Laya.Stat.savedRenderBatches += elementCount - renderBatchCount;
  15360. Laya.Stat.trianglesFaces += batchIndexCount / 3;
  15361. }
  15362. }
  15363. SubMeshDynamicBatch.maxAllowVertexCount = 10;
  15364. SubMeshDynamicBatch.maxAllowAttribueCount = 900;
  15365. SubMeshDynamicBatch.maxIndicesCount = 32000;
  15366. class MeshRenderDynamicBatchManager extends DynamicBatchManager {
  15367. constructor() {
  15368. super();
  15369. this._instanceBatchOpaqueMarks = [];
  15370. this._vertexBatchOpaqueMarks = [];
  15371. this._cacheBufferStates = [];
  15372. this._updateCountMark = 0;
  15373. }
  15374. getInstanceBatchOpaquaMark(receiveShadow, materialID, subMeshID, invertFace) {
  15375. var instanceReceiveShadowMarks = (this._instanceBatchOpaqueMarks[receiveShadow ? 0 : 1]) || (this._instanceBatchOpaqueMarks[receiveShadow ? 0 : 1] = []);
  15376. var instanceMaterialMarks = (instanceReceiveShadowMarks[materialID]) || (instanceReceiveShadowMarks[materialID] = []);
  15377. var instancSubMeshMarks = (instanceMaterialMarks[subMeshID]) || (instanceMaterialMarks[subMeshID] = []);
  15378. return instancSubMeshMarks[invertFace ? 1 : 0] || (instancSubMeshMarks[invertFace ? 1 : 0] = new BatchMark());
  15379. }
  15380. getVertexBatchOpaquaMark(lightMapIndex, receiveShadow, materialID, verDecID) {
  15381. var dynLightMapMarks = (this._vertexBatchOpaqueMarks[lightMapIndex]) || (this._vertexBatchOpaqueMarks[lightMapIndex] = []);
  15382. var dynReceiveShadowMarks = (dynLightMapMarks[receiveShadow ? 0 : 1]) || (dynLightMapMarks[receiveShadow ? 0 : 1] = []);
  15383. var dynMaterialMarks = (dynReceiveShadowMarks[materialID]) || (dynReceiveShadowMarks[materialID] = []);
  15384. return dynMaterialMarks[verDecID] || (dynMaterialMarks[verDecID] = new BatchMark());
  15385. }
  15386. _getBufferState(vertexDeclaration) {
  15387. var bufferState = this._cacheBufferStates[vertexDeclaration.id];
  15388. if (!bufferState) {
  15389. var instance = SubMeshDynamicBatch.instance;
  15390. bufferState = new BufferState();
  15391. bufferState.bind();
  15392. var vertexBuffer = instance._vertexBuffer;
  15393. vertexBuffer.vertexDeclaration = vertexDeclaration;
  15394. bufferState.applyVertexBuffer(vertexBuffer);
  15395. bufferState.applyIndexBuffer(instance._indexBuffer);
  15396. bufferState.unBind();
  15397. this._cacheBufferStates[vertexDeclaration.id] = bufferState;
  15398. }
  15399. return bufferState;
  15400. }
  15401. _getBatchRenderElementFromPool() {
  15402. var renderElement = this._batchRenderElementPool[this._batchRenderElementPoolIndex++];
  15403. if (!renderElement) {
  15404. renderElement = new SubMeshRenderElement();
  15405. this._batchRenderElementPool[this._batchRenderElementPoolIndex - 1] = renderElement;
  15406. renderElement.vertexBatchElementList = new SingletonList();
  15407. renderElement.instanceBatchElementList = new SingletonList();
  15408. }
  15409. return renderElement;
  15410. }
  15411. _clear() {
  15412. super._clear();
  15413. this._updateCountMark++;
  15414. }
  15415. }
  15416. MeshRenderDynamicBatchManager.instance = new MeshRenderDynamicBatchManager();
  15417. class MeshSprite3D extends RenderableSprite3D {
  15418. static __init__() {
  15419. MeshSprite3DShaderDeclaration.SHADERDEFINE_UV0 = Shader3D.getDefineByName("UV");
  15420. MeshSprite3DShaderDeclaration.SHADERDEFINE_COLOR = Shader3D.getDefineByName("COLOR");
  15421. MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1 = Shader3D.getDefineByName("UV1");
  15422. MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE = Shader3D.getDefineByName("GPU_INSTANCE");
  15423. StaticBatchManager._registerManager(MeshRenderStaticBatchManager.instance);
  15424. DynamicBatchManager._registerManager(MeshRenderDynamicBatchManager.instance);
  15425. }
  15426. get meshFilter() {
  15427. return this._meshFilter;
  15428. }
  15429. get meshRenderer() {
  15430. return this._render;
  15431. }
  15432. constructor(mesh = null, name = null) {
  15433. super(name);
  15434. this._meshFilter = new MeshFilter(this);
  15435. this._render = new MeshRenderer(this);
  15436. (mesh) && (this._meshFilter.sharedMesh = mesh);
  15437. }
  15438. _parse(data, spriteMap) {
  15439. super._parse(data, spriteMap);
  15440. var render = this.meshRenderer;
  15441. var lightmapIndex = data.lightmapIndex;
  15442. (lightmapIndex != null) && (render.lightmapIndex = lightmapIndex);
  15443. var lightmapScaleOffsetArray = data.lightmapScaleOffset;
  15444. (lightmapScaleOffsetArray) && (render.lightmapScaleOffset = new Vector4(lightmapScaleOffsetArray[0], lightmapScaleOffsetArray[1], lightmapScaleOffsetArray[2], lightmapScaleOffsetArray[3]));
  15445. (data.meshPath != undefined) && (this.meshFilter.sharedMesh = Laya.Loader.getRes(data.meshPath));
  15446. (data.enableRender != undefined) && (this.meshRenderer.enable = data.enableRender);
  15447. var materials = data.materials;
  15448. if (materials) {
  15449. var sharedMaterials = render.sharedMaterials;
  15450. var materialCount = materials.length;
  15451. sharedMaterials.length = materialCount;
  15452. for (var i = 0; i < materialCount; i++) {
  15453. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  15454. }
  15455. render.sharedMaterials = sharedMaterials;
  15456. }
  15457. }
  15458. _addToInitStaticBatchManager() {
  15459. if (this.meshFilter.sharedMesh)
  15460. MeshRenderStaticBatchManager.instance._addBatchSprite(this);
  15461. }
  15462. _cloneTo(destObject, rootSprite, dstSprite) {
  15463. var meshSprite3D = destObject;
  15464. meshSprite3D._meshFilter.sharedMesh = this._meshFilter.sharedMesh;
  15465. var meshRender = this._render;
  15466. var destMeshRender = meshSprite3D._render;
  15467. destMeshRender.enable = meshRender.enable;
  15468. destMeshRender.sharedMaterials = meshRender.sharedMaterials;
  15469. destMeshRender.castShadow = meshRender.castShadow;
  15470. var lightmapScaleOffset = meshRender.lightmapScaleOffset;
  15471. lightmapScaleOffset && (destMeshRender.lightmapScaleOffset = lightmapScaleOffset.clone());
  15472. destMeshRender.lightmapIndex = meshRender.lightmapIndex;
  15473. destMeshRender.receiveShadow = meshRender.receiveShadow;
  15474. destMeshRender.sortingFudge = meshRender.sortingFudge;
  15475. super._cloneTo(destObject, rootSprite, dstSprite);
  15476. }
  15477. destroy(destroyChild = true) {
  15478. if (this.destroyed)
  15479. return;
  15480. super.destroy(destroyChild);
  15481. this._meshFilter.destroy();
  15482. }
  15483. _create() {
  15484. return new MeshSprite3D();
  15485. }
  15486. }
  15487. class GradientMode {
  15488. }
  15489. GradientMode.Blend = 0;
  15490. GradientMode.Fixed = 1;
  15491. class Gradient {
  15492. constructor(maxColorRGBKeyCount, maxColorAlphaKeyCount) {
  15493. this._mode = 0;
  15494. this._maxColorRGBKeysCount = 0;
  15495. this._maxColorAlphaKeysCount = 0;
  15496. this._colorRGBKeysCount = 0;
  15497. this._colorAlphaKeysCount = 0;
  15498. this._alphaElements = null;
  15499. this._rgbElements = null;
  15500. this._maxColorRGBKeysCount = maxColorRGBKeyCount;
  15501. this._maxColorAlphaKeysCount = maxColorAlphaKeyCount;
  15502. this._rgbElements = new Float32Array(maxColorRGBKeyCount * 4);
  15503. this._alphaElements = new Float32Array(maxColorAlphaKeyCount * 2);
  15504. }
  15505. get mode() {
  15506. return this._mode;
  15507. }
  15508. set mode(value) {
  15509. this._mode = value;
  15510. }
  15511. get colorRGBKeysCount() {
  15512. return this._colorRGBKeysCount;
  15513. }
  15514. get colorAlphaKeysCount() {
  15515. return this._colorAlphaKeysCount;
  15516. }
  15517. get maxColorRGBKeysCount() {
  15518. return this._maxColorRGBKeysCount;
  15519. }
  15520. get maxColorAlphaKeysCount() {
  15521. return this._maxColorAlphaKeysCount;
  15522. }
  15523. addColorRGB(key, value) {
  15524. if (this._colorRGBKeysCount < this._maxColorRGBKeysCount) {
  15525. var offset = this._colorRGBKeysCount * 4;
  15526. this._rgbElements[offset] = key;
  15527. this._rgbElements[offset + 1] = value.r;
  15528. this._rgbElements[offset + 2] = value.g;
  15529. this._rgbElements[offset + 3] = value.b;
  15530. this._colorRGBKeysCount++;
  15531. }
  15532. else {
  15533. console.warn("Gradient:warning:data count must lessEqual than " + this._maxColorRGBKeysCount);
  15534. }
  15535. }
  15536. addColorAlpha(key, value) {
  15537. if (this._colorAlphaKeysCount < this._maxColorAlphaKeysCount) {
  15538. var offset = this._colorAlphaKeysCount * 2;
  15539. this._alphaElements[offset] = key;
  15540. this._alphaElements[offset + 1] = value;
  15541. this._colorAlphaKeysCount++;
  15542. }
  15543. else {
  15544. console.warn("Gradient:warning:data count must lessEqual than " + this._maxColorAlphaKeysCount);
  15545. }
  15546. }
  15547. updateColorRGB(index, key, value) {
  15548. if (index < this._colorRGBKeysCount) {
  15549. var offset = index * 4;
  15550. this._rgbElements[offset] = key;
  15551. this._rgbElements[offset + 1] = value.r;
  15552. this._rgbElements[offset + 2] = value.g;
  15553. this._rgbElements[offset + 3] = value.b;
  15554. }
  15555. else {
  15556. console.warn("Gradient:warning:index must lessEqual than colorRGBKeysCount:" + this._colorRGBKeysCount);
  15557. }
  15558. }
  15559. updateColorAlpha(index, key, value) {
  15560. if (index < this._colorAlphaKeysCount) {
  15561. var offset = index * 2;
  15562. this._alphaElements[offset] = key;
  15563. this._alphaElements[offset + 1] = value;
  15564. }
  15565. else {
  15566. console.warn("Gradient:warning:index must lessEqual than colorAlphaKeysCount:" + this._colorAlphaKeysCount);
  15567. }
  15568. }
  15569. evaluateColorRGB(lerpFactor, out, startSearchIndex = 0, reverseSearch = false) {
  15570. lerpFactor = Math.min(Math.max(lerpFactor, 0.0), 1.0);
  15571. var rgbElements = this._rgbElements;
  15572. var curIndex = startSearchIndex;
  15573. if (reverseSearch) {
  15574. for (var i = curIndex; i >= 0; i--) {
  15575. var offset = i * 4;
  15576. var left = rgbElements[offset];
  15577. if (lerpFactor === left) {
  15578. out.r = rgbElements[offset + 1];
  15579. out.g = rgbElements[offset + 2];
  15580. out.b = rgbElements[offset + 3];
  15581. return curIndex;
  15582. }
  15583. switch (this._mode) {
  15584. case GradientMode.Blend:
  15585. if (lerpFactor > left) {
  15586. var right = rgbElements[offset + 4];
  15587. if (lerpFactor > right)
  15588. throw "Gradient:wrong startSearchIndex.";
  15589. var diff = right - left;
  15590. var y1 = right - lerpFactor;
  15591. var y2 = lerpFactor - left;
  15592. out.r = (y1 * rgbElements[offset + 1] + y2 * rgbElements[offset + 5]) / diff;
  15593. out.g = (y1 * rgbElements[offset + 2] + y2 * rgbElements[offset + 6]) / diff;
  15594. out.b = (y1 * rgbElements[offset + 3] + y2 * rgbElements[offset + 7]) / diff;
  15595. return curIndex;
  15596. }
  15597. else {
  15598. curIndex--;
  15599. continue;
  15600. }
  15601. case GradientMode.Fixed:
  15602. if (lerpFactor > left) {
  15603. if (lerpFactor > rgbElements[offset + 4])
  15604. throw "Gradient:wrong startSearchIndex.";
  15605. out.r = rgbElements[offset + 5];
  15606. out.g = rgbElements[offset + 6];
  15607. out.b = rgbElements[offset + 7];
  15608. return curIndex;
  15609. }
  15610. else {
  15611. curIndex--;
  15612. continue;
  15613. }
  15614. default:
  15615. throw "Gradient:unknown mode.";
  15616. }
  15617. }
  15618. }
  15619. else {
  15620. for (var i = 0, n = this._rgbElements.length; i < n; i++) {
  15621. offset = i * 4;
  15622. var right = rgbElements[offset];
  15623. if (lerpFactor === right) {
  15624. out.r = rgbElements[offset + 1];
  15625. out.g = rgbElements[offset + 2];
  15626. out.b = rgbElements[offset + 3];
  15627. return curIndex;
  15628. }
  15629. switch (this._mode) {
  15630. case GradientMode.Blend:
  15631. if (lerpFactor < right) {
  15632. var left = rgbElements[offset - 4];
  15633. if (lerpFactor < left)
  15634. throw "Gradient:wrong startSearchIndex.";
  15635. var diff = right - left;
  15636. var y1 = right - lerpFactor;
  15637. var y2 = lerpFactor - left;
  15638. out.r = (y1 * rgbElements[offset - 3] + y2 * rgbElements[offset + 1]) / diff;
  15639. out.g = (y1 * rgbElements[offset - 2] + y2 * rgbElements[offset + 2]) / diff;
  15640. out.b = (y1 * rgbElements[offset - 1] + y2 * rgbElements[offset + 3]) / diff;
  15641. return curIndex;
  15642. }
  15643. else {
  15644. curIndex++;
  15645. continue;
  15646. }
  15647. case GradientMode.Fixed:
  15648. if (lerpFactor < right) {
  15649. if (lerpFactor < rgbElements[offset - 4])
  15650. throw "Gradient:wrong startSearchIndex.";
  15651. out.r = rgbElements[offset + 1];
  15652. out.g = rgbElements[offset + 2];
  15653. out.b = rgbElements[offset + 3];
  15654. return curIndex;
  15655. }
  15656. else {
  15657. curIndex++;
  15658. continue;
  15659. }
  15660. default:
  15661. throw "Gradient:unknown mode.";
  15662. }
  15663. }
  15664. }
  15665. return curIndex;
  15666. }
  15667. evaluateColorAlpha(lerpFactor, outColor, startSearchIndex = 0, reverseSearch = false) {
  15668. lerpFactor = Math.min(Math.max(lerpFactor, 0.0), 1.0);
  15669. var alphaElements = this._alphaElements;
  15670. var curIndex = startSearchIndex;
  15671. if (reverseSearch) {
  15672. for (var i = curIndex; i >= 0; i--) {
  15673. var offset = i * 2;
  15674. var left = alphaElements[offset];
  15675. if (lerpFactor === left) {
  15676. outColor.a = alphaElements[offset + 1];
  15677. return curIndex;
  15678. }
  15679. switch (this._mode) {
  15680. case GradientMode.Blend:
  15681. if (lerpFactor > left) {
  15682. var right = alphaElements[offset + 2];
  15683. if (lerpFactor > right)
  15684. throw "Gradient:wrong startSearchIndex.";
  15685. var diff = right - left;
  15686. var x1 = right - lerpFactor;
  15687. var x2 = lerpFactor - left;
  15688. outColor.a = (x1 * alphaElements[offset + 1] + x2 * alphaElements[offset + 3]) / diff;
  15689. return curIndex;
  15690. }
  15691. else {
  15692. curIndex--;
  15693. continue;
  15694. }
  15695. case GradientMode.Fixed:
  15696. if (lerpFactor > left) {
  15697. if (lerpFactor > alphaElements[offset + 2])
  15698. throw "Gradient:wrong startSearchIndex.";
  15699. outColor.a = alphaElements[offset + 3];
  15700. return curIndex;
  15701. }
  15702. else {
  15703. curIndex--;
  15704. continue;
  15705. }
  15706. default:
  15707. throw "Gradient:unknown mode.";
  15708. }
  15709. }
  15710. }
  15711. else {
  15712. for (var i = curIndex, n = this._alphaElements.length; i < n; i++) {
  15713. var offset = i * 2;
  15714. var right = alphaElements[offset];
  15715. if (lerpFactor === right) {
  15716. outColor.a = alphaElements[offset + 1];
  15717. return curIndex;
  15718. }
  15719. switch (this._mode) {
  15720. case GradientMode.Blend:
  15721. if (lerpFactor < right) {
  15722. var left = alphaElements[offset - 2];
  15723. if (lerpFactor < left)
  15724. throw "Gradient:wrong startSearchIndex.";
  15725. var diff = right - left;
  15726. var x1 = right - lerpFactor;
  15727. var x2 = lerpFactor - left;
  15728. outColor.a = (x1 * alphaElements[offset - 1] + x2 * alphaElements[offset + 1]) / diff;
  15729. return curIndex;
  15730. }
  15731. else {
  15732. curIndex++;
  15733. continue;
  15734. }
  15735. case GradientMode.Fixed:
  15736. if (lerpFactor < right) {
  15737. if (lerpFactor < alphaElements[offset - 2])
  15738. throw "Gradient:wrong startSearchIndex.";
  15739. outColor.a = alphaElements[offset + 1];
  15740. return curIndex;
  15741. }
  15742. else {
  15743. curIndex++;
  15744. continue;
  15745. }
  15746. default:
  15747. throw "Gradient:unknown mode.";
  15748. }
  15749. }
  15750. }
  15751. return curIndex;
  15752. }
  15753. cloneTo(destObject) {
  15754. var destGradientDataColor = destObject;
  15755. var i, n;
  15756. destGradientDataColor._colorAlphaKeysCount = this._colorAlphaKeysCount;
  15757. var destAlphaElements = destGradientDataColor._alphaElements;
  15758. for (i = 0, n = this._alphaElements.length; i < n; i++)
  15759. destAlphaElements[i] = this._alphaElements[i];
  15760. destGradientDataColor._colorRGBKeysCount = this._colorRGBKeysCount;
  15761. var destRGBElements = destGradientDataColor._rgbElements;
  15762. for (i = 0, n = this._rgbElements.length; i < n; i++)
  15763. destRGBElements[i] = this._rgbElements[i];
  15764. }
  15765. clone() {
  15766. var destGradientDataColor = new Gradient(this._maxColorRGBKeysCount, this._maxColorAlphaKeysCount);
  15767. this.cloneTo(destGradientDataColor);
  15768. return destGradientDataColor;
  15769. }
  15770. }
  15771. class ShurikenParticleMaterial extends BaseMaterial {
  15772. constructor() {
  15773. super();
  15774. this.setShaderName("PARTICLESHURIKEN");
  15775. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  15776. this.renderMode = ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED;
  15777. }
  15778. static __initDefine__() {
  15779. ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP = Shader3D.getDefineByName("DIFFUSEMAP");
  15780. ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR = Shader3D.getDefineByName("TINTCOLOR");
  15781. ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  15782. ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  15783. }
  15784. get _TintColorR() {
  15785. return this._color.x;
  15786. }
  15787. set _TintColorR(value) {
  15788. this._color.x = value;
  15789. this.color = this._color;
  15790. }
  15791. get _TintColorG() {
  15792. return this._color.y;
  15793. }
  15794. set _TintColorG(value) {
  15795. this._color.y = value;
  15796. this.color = this._color;
  15797. }
  15798. get _TintColorB() {
  15799. return this._color.z;
  15800. }
  15801. set _TintColorB(value) {
  15802. this._color.z = value;
  15803. this.color = this._color;
  15804. }
  15805. get _TintColorA() {
  15806. return this._color.w;
  15807. }
  15808. set _TintColorA(value) {
  15809. this._color.w = value;
  15810. this.color = this._color;
  15811. }
  15812. get _MainTex_STX() {
  15813. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).x;
  15814. }
  15815. set _MainTex_STX(x) {
  15816. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  15817. tilOff.x = x;
  15818. this.tilingOffset = tilOff;
  15819. }
  15820. get _MainTex_STY() {
  15821. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).y;
  15822. }
  15823. set _MainTex_STY(y) {
  15824. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  15825. tilOff.y = y;
  15826. this.tilingOffset = tilOff;
  15827. }
  15828. get _MainTex_STZ() {
  15829. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).z;
  15830. }
  15831. set _MainTex_STZ(z) {
  15832. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  15833. tilOff.z = z;
  15834. this.tilingOffset = tilOff;
  15835. }
  15836. get _MainTex_STW() {
  15837. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).w;
  15838. }
  15839. set _MainTex_STW(w) {
  15840. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  15841. tilOff.w = w;
  15842. this.tilingOffset = tilOff;
  15843. }
  15844. set renderMode(value) {
  15845. switch (value) {
  15846. case ShurikenParticleMaterial.RENDERMODE_ADDTIVE:
  15847. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  15848. this.depthWrite = false;
  15849. this.cull = RenderState.CULL_NONE;
  15850. this.blend = RenderState.BLEND_ENABLE_ALL;
  15851. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  15852. this.blendDst = RenderState.BLENDPARAM_ONE;
  15853. this.alphaTest = false;
  15854. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG);
  15855. break;
  15856. case ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED:
  15857. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  15858. this.depthWrite = false;
  15859. this.cull = RenderState.CULL_NONE;
  15860. this.blend = RenderState.BLEND_ENABLE_ALL;
  15861. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  15862. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  15863. this.alphaTest = false;
  15864. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG);
  15865. break;
  15866. default:
  15867. throw new Error("ShurikenParticleMaterial : renderMode value error.");
  15868. }
  15869. }
  15870. get colorR() {
  15871. return this._TintColorR;
  15872. }
  15873. set colorR(value) {
  15874. this._TintColorR = value;
  15875. }
  15876. get colorG() {
  15877. return this._TintColorG;
  15878. }
  15879. set colorG(value) {
  15880. this._TintColorG = value;
  15881. }
  15882. get colorB() {
  15883. return this._TintColorB;
  15884. }
  15885. set colorB(value) {
  15886. this._TintColorB = value;
  15887. }
  15888. get colorA() {
  15889. return this._TintColorA;
  15890. }
  15891. set colorA(value) {
  15892. this._TintColorA = value;
  15893. }
  15894. get color() {
  15895. return this._shaderValues.getVector(ShurikenParticleMaterial.TINTCOLOR);
  15896. }
  15897. set color(value) {
  15898. if (value)
  15899. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR);
  15900. else
  15901. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR);
  15902. this._shaderValues.setVector(ShurikenParticleMaterial.TINTCOLOR, value);
  15903. }
  15904. get tilingOffsetX() {
  15905. return this._MainTex_STX;
  15906. }
  15907. set tilingOffsetX(x) {
  15908. this._MainTex_STX = x;
  15909. }
  15910. get tilingOffsetY() {
  15911. return this._MainTex_STY;
  15912. }
  15913. set tilingOffsetY(y) {
  15914. this._MainTex_STY = y;
  15915. }
  15916. get tilingOffsetZ() {
  15917. return this._MainTex_STZ;
  15918. }
  15919. set tilingOffsetZ(z) {
  15920. this._MainTex_STZ = z;
  15921. }
  15922. get tilingOffsetW() {
  15923. return this._MainTex_STW;
  15924. }
  15925. set tilingOffsetW(w) {
  15926. this._MainTex_STW = w;
  15927. }
  15928. get tilingOffset() {
  15929. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  15930. }
  15931. set tilingOffset(value) {
  15932. if (value) {
  15933. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  15934. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  15935. else
  15936. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  15937. }
  15938. else {
  15939. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  15940. }
  15941. this._shaderValues.setVector(ShurikenParticleMaterial.TILINGOFFSET, value);
  15942. }
  15943. get texture() {
  15944. return this._shaderValues.getTexture(ShurikenParticleMaterial.DIFFUSETEXTURE);
  15945. }
  15946. set texture(value) {
  15947. if (value)
  15948. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP);
  15949. else
  15950. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP);
  15951. this._shaderValues.setTexture(ShurikenParticleMaterial.DIFFUSETEXTURE, value);
  15952. }
  15953. get depthWrite() {
  15954. return this._shaderValues.getBool(ShurikenParticleMaterial.DEPTH_WRITE);
  15955. }
  15956. set depthWrite(value) {
  15957. this._shaderValues.setBool(ShurikenParticleMaterial.DEPTH_WRITE, value);
  15958. }
  15959. get cull() {
  15960. return this._shaderValues.getInt(ShurikenParticleMaterial.CULL);
  15961. }
  15962. set cull(value) {
  15963. this._shaderValues.setInt(ShurikenParticleMaterial.CULL, value);
  15964. }
  15965. get blend() {
  15966. return this._shaderValues.getInt(ShurikenParticleMaterial.BLEND);
  15967. }
  15968. set blend(value) {
  15969. this._shaderValues.setInt(ShurikenParticleMaterial.BLEND, value);
  15970. }
  15971. get blendSrc() {
  15972. return this._shaderValues.getInt(ShurikenParticleMaterial.BLEND_SRC);
  15973. }
  15974. set blendSrc(value) {
  15975. this._shaderValues.setInt(ShurikenParticleMaterial.BLEND_SRC, value);
  15976. }
  15977. get blendDst() {
  15978. return this._shaderValues.getInt(ShurikenParticleMaterial.BLEND_DST);
  15979. }
  15980. set blendDst(value) {
  15981. this._shaderValues.setInt(ShurikenParticleMaterial.BLEND_DST, value);
  15982. }
  15983. get depthTest() {
  15984. return this._shaderValues.getInt(ShurikenParticleMaterial.DEPTH_TEST);
  15985. }
  15986. set depthTest(value) {
  15987. this._shaderValues.setInt(ShurikenParticleMaterial.DEPTH_TEST, value);
  15988. }
  15989. clone() {
  15990. var dest = new ShurikenParticleMaterial();
  15991. this.cloneTo(dest);
  15992. return dest;
  15993. }
  15994. }
  15995. ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED = 0;
  15996. ShurikenParticleMaterial.RENDERMODE_ADDTIVE = 1;
  15997. ShurikenParticleMaterial.DIFFUSETEXTURE = Shader3D.propertyNameToID("u_texture");
  15998. ShurikenParticleMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_Tintcolor");
  15999. ShurikenParticleMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  16000. ShurikenParticleMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  16001. ShurikenParticleMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  16002. ShurikenParticleMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  16003. ShurikenParticleMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  16004. ShurikenParticleMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  16005. ShurikenParticleMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  16006. class Physics3DUtils {
  16007. constructor() {
  16008. }
  16009. static setColliderCollision(collider1, collider2, collsion) {
  16010. }
  16011. static getIColliderCollision(collider1, collider2) {
  16012. return false;
  16013. }
  16014. }
  16015. Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER = 0x1;
  16016. Physics3DUtils.COLLISIONFILTERGROUP_STATICFILTER = 0x2;
  16017. Physics3DUtils.COLLISIONFILTERGROUP_KINEMATICFILTER = 0x4;
  16018. Physics3DUtils.COLLISIONFILTERGROUP_DEBRISFILTER = 0x8;
  16019. Physics3DUtils.COLLISIONFILTERGROUP_SENSORTRIGGER = 0x10;
  16020. Physics3DUtils.COLLISIONFILTERGROUP_CHARACTERFILTER = 0x20;
  16021. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER1 = 0x40;
  16022. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER2 = 0x80;
  16023. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER3 = 0x100;
  16024. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER4 = 0x200;
  16025. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER5 = 0x400;
  16026. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER6 = 0x800;
  16027. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER7 = 0x1000;
  16028. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER8 = 0x2000;
  16029. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER9 = 0x4000;
  16030. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER10 = 0x8000;
  16031. Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER = -1;
  16032. Physics3DUtils.gravity = new Vector3(0, -9.81, 0);
  16033. class ShuriKenParticle3DShaderDeclaration {
  16034. }
  16035. ShuriKenParticle3DShaderDeclaration.WORLDPOSITION = Shader3D.propertyNameToID("u_WorldPosition");
  16036. ShuriKenParticle3DShaderDeclaration.WORLDROTATION = Shader3D.propertyNameToID("u_WorldRotation");
  16037. ShuriKenParticle3DShaderDeclaration.POSITIONSCALE = Shader3D.propertyNameToID("u_PositionScale");
  16038. ShuriKenParticle3DShaderDeclaration.SIZESCALE = Shader3D.propertyNameToID("u_SizeScale");
  16039. ShuriKenParticle3DShaderDeclaration.SCALINGMODE = Shader3D.propertyNameToID("u_ScalingMode");
  16040. ShuriKenParticle3DShaderDeclaration.GRAVITY = Shader3D.propertyNameToID("u_Gravity");
  16041. ShuriKenParticle3DShaderDeclaration.THREEDSTARTROTATION = Shader3D.propertyNameToID("u_ThreeDStartRotation");
  16042. ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDLENGTHSCALE = Shader3D.propertyNameToID("u_StretchedBillboardLengthScale");
  16043. ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDSPEEDSCALE = Shader3D.propertyNameToID("u_StretchedBillboardSpeedScale");
  16044. ShuriKenParticle3DShaderDeclaration.SIMULATIONSPACE = Shader3D.propertyNameToID("u_SimulationSpace");
  16045. ShuriKenParticle3DShaderDeclaration.CURRENTTIME = Shader3D.propertyNameToID("u_CurrentTime");
  16046. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST = Shader3D.propertyNameToID("u_VOLVelocityConst");
  16047. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX = Shader3D.propertyNameToID("u_VOLVelocityGradientX");
  16048. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY = Shader3D.propertyNameToID("u_VOLVelocityGradientY");
  16049. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ = Shader3D.propertyNameToID("u_VOLVelocityGradientZ");
  16050. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONSTMAX = Shader3D.propertyNameToID("u_VOLVelocityConstMax");
  16051. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTXMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxX");
  16052. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTYMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxY");
  16053. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxZ");
  16054. ShuriKenParticle3DShaderDeclaration.VOLSPACETYPE = Shader3D.propertyNameToID("u_VOLSpaceType");
  16055. ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS = Shader3D.propertyNameToID("u_ColorOverLifeGradientAlphas");
  16056. ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS = Shader3D.propertyNameToID("u_ColorOverLifeGradientColors");
  16057. ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS = Shader3D.propertyNameToID("u_MaxColorOverLifeGradientAlphas");
  16058. ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS = Shader3D.propertyNameToID("u_MaxColorOverLifeGradientColors");
  16059. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT = Shader3D.propertyNameToID("u_SOLSizeGradient");
  16060. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX = Shader3D.propertyNameToID("u_SOLSizeGradientX");
  16061. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY = Shader3D.propertyNameToID("u_SOLSizeGradientY");
  16062. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ = Shader3D.propertyNameToID("u_SOLSizeGradientZ");
  16063. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientMax = Shader3D.propertyNameToID("u_SOLSizeGradientMax");
  16064. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTXMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxX");
  16065. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTYMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxY");
  16066. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxZ");
  16067. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST = Shader3D.propertyNameToID("u_ROLAngularVelocityConst");
  16068. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE = Shader3D.propertyNameToID("u_ROLAngularVelocityConstSeprarate");
  16069. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT = Shader3D.propertyNameToID("u_ROLAngularVelocityGradient");
  16070. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientX");
  16071. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientY");
  16072. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientZ");
  16073. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityConstMax");
  16074. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAXSEPRARATE = Shader3D.propertyNameToID("u_ROLAngularVelocityConstMaxSeprarate");
  16075. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMax");
  16076. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTXMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxX");
  16077. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTYMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxY");
  16078. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxZ");
  16079. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTWMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxW");
  16080. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONCYCLES = Shader3D.propertyNameToID("u_TSACycles");
  16081. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONSUBUVLENGTH = Shader3D.propertyNameToID("u_TSASubUVLength");
  16082. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS = Shader3D.propertyNameToID("u_TSAGradientUVs");
  16083. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTMAXUVS = Shader3D.propertyNameToID("u_TSAMaxGradientUVs");
  16084. class ShurikenParticleRenderer extends BaseRender {
  16085. constructor(owner) {
  16086. super(owner);
  16087. this._finalGravity = new Vector3();
  16088. this._tempRotationMatrix = new Matrix4x4();
  16089. this._renderMode = 0;
  16090. this._mesh = null;
  16091. this.stretchedBillboardCameraSpeedScale = 0;
  16092. this.stretchedBillboardSpeedScale = 0;
  16093. this.stretchedBillboardLengthScale = 0;
  16094. this._defaultBoundBox = new BoundBox(new Vector3(), new Vector3());
  16095. this._renderMode = -1;
  16096. this.stretchedBillboardCameraSpeedScale = 0.0;
  16097. this.stretchedBillboardSpeedScale = 0.0;
  16098. this.stretchedBillboardLengthScale = 1.0;
  16099. this._supportOctree = false;
  16100. }
  16101. get renderMode() {
  16102. return this._renderMode;
  16103. }
  16104. get mesh() {
  16105. return this._mesh;
  16106. }
  16107. set mesh(value) {
  16108. if (this._mesh !== value) {
  16109. (this._mesh) && (this._mesh._removeReference());
  16110. this._mesh = value;
  16111. (value) && (value._addReference());
  16112. this._owner.particleSystem._initBufferDatas();
  16113. }
  16114. }
  16115. set renderMode(value) {
  16116. if (this._renderMode !== value) {
  16117. var defineDatas = this._shaderValues;
  16118. switch (this._renderMode) {
  16119. case 0:
  16120. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD);
  16121. break;
  16122. case 1:
  16123. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD);
  16124. break;
  16125. case 2:
  16126. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD);
  16127. break;
  16128. case 3:
  16129. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD);
  16130. break;
  16131. case 4:
  16132. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH);
  16133. break;
  16134. }
  16135. this._renderMode = value;
  16136. switch (value) {
  16137. case 0:
  16138. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD);
  16139. break;
  16140. case 1:
  16141. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD);
  16142. break;
  16143. case 2:
  16144. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD);
  16145. break;
  16146. case 3:
  16147. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD);
  16148. break;
  16149. case 4:
  16150. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH);
  16151. break;
  16152. default:
  16153. throw new Error("ShurikenParticleRender: unknown renderMode Value.");
  16154. }
  16155. this._owner.particleSystem._initBufferDatas();
  16156. }
  16157. }
  16158. _calculateBoundingBox() {
  16159. var min = this._bounds.getMin();
  16160. min.x = -Number.MAX_VALUE;
  16161. min.y = -Number.MAX_VALUE;
  16162. min.z = -Number.MAX_VALUE;
  16163. this._bounds.setMin(min);
  16164. var max = this._bounds.getMax();
  16165. max.x = Number.MAX_VALUE;
  16166. max.y = Number.MAX_VALUE;
  16167. max.z = Number.MAX_VALUE;
  16168. this._bounds.setMax(max);
  16169. if (Laya.Render.supportWebGLPlusCulling) {
  16170. var min = this._bounds.getMin();
  16171. var max = this._bounds.getMax();
  16172. var buffer = FrustumCulling._cullingBuffer;
  16173. buffer[this._cullingBufferIndex + 1] = min.x;
  16174. buffer[this._cullingBufferIndex + 2] = min.y;
  16175. buffer[this._cullingBufferIndex + 3] = min.z;
  16176. buffer[this._cullingBufferIndex + 4] = max.x;
  16177. buffer[this._cullingBufferIndex + 5] = max.y;
  16178. buffer[this._cullingBufferIndex + 6] = max.z;
  16179. }
  16180. }
  16181. _needRender(boundFrustum, context) {
  16182. if (boundFrustum) {
  16183. if (boundFrustum.intersects(this.bounds._getBoundBox())) {
  16184. if (this._owner.particleSystem.isAlive)
  16185. return true;
  16186. else
  16187. return false;
  16188. }
  16189. else {
  16190. return false;
  16191. }
  16192. }
  16193. else {
  16194. return true;
  16195. }
  16196. }
  16197. _renderUpdate(context, transfrom) {
  16198. var particleSystem = this._owner.particleSystem;
  16199. var sv = this._shaderValues;
  16200. var transform = this._owner.transform;
  16201. switch (particleSystem.simulationSpace) {
  16202. case 0:
  16203. break;
  16204. case 1:
  16205. sv.setVector3(ShuriKenParticle3DShaderDeclaration.WORLDPOSITION, transform.position);
  16206. sv.setQuaternion(ShuriKenParticle3DShaderDeclaration.WORLDROTATION, transform.rotation);
  16207. break;
  16208. default:
  16209. throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid.");
  16210. }
  16211. switch (particleSystem.scaleMode) {
  16212. case 0:
  16213. var scale = transform.getWorldLossyScale();
  16214. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, scale);
  16215. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, scale);
  16216. break;
  16217. case 1:
  16218. var localScale = transform.localScale;
  16219. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, localScale);
  16220. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, localScale);
  16221. break;
  16222. case 2:
  16223. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, transform.getWorldLossyScale());
  16224. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, Vector3._ONE);
  16225. break;
  16226. }
  16227. Vector3.scale(Physics3DUtils.gravity, particleSystem.gravityModifier, this._finalGravity);
  16228. sv.setVector3(ShuriKenParticle3DShaderDeclaration.GRAVITY, this._finalGravity);
  16229. sv.setInt(ShuriKenParticle3DShaderDeclaration.SIMULATIONSPACE, particleSystem.simulationSpace);
  16230. sv.setBool(ShuriKenParticle3DShaderDeclaration.THREEDSTARTROTATION, particleSystem.threeDStartRotation);
  16231. sv.setInt(ShuriKenParticle3DShaderDeclaration.SCALINGMODE, particleSystem.scaleMode);
  16232. sv.setNumber(ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDLENGTHSCALE, this.stretchedBillboardLengthScale);
  16233. sv.setNumber(ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDSPEEDSCALE, this.stretchedBillboardSpeedScale);
  16234. sv.setNumber(ShuriKenParticle3DShaderDeclaration.CURRENTTIME, particleSystem._currentTime);
  16235. }
  16236. get bounds() {
  16237. if (this._boundsChange) {
  16238. this._calculateBoundingBox();
  16239. this._boundsChange = false;
  16240. }
  16241. return this._bounds;
  16242. }
  16243. _destroy() {
  16244. super._destroy();
  16245. (this._mesh) && (this._mesh._removeReference(), this._mesh = null);
  16246. }
  16247. }
  16248. class VertexShuriKenParticle {
  16249. constructor() {
  16250. }
  16251. }
  16252. VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0 = 0;
  16253. VertexShuriKenParticle.PARTICLE_POSITION0 = 1;
  16254. VertexShuriKenParticle.PARTICLE_COLOR0 = 2;
  16255. VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0 = 3;
  16256. VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME = 4;
  16257. VertexShuriKenParticle.PARTICLE_DIRECTIONTIME = 5;
  16258. VertexShuriKenParticle.PARTICLE_STARTCOLOR0 = 6;
  16259. VertexShuriKenParticle.PARTICLE_ENDCOLOR0 = 7;
  16260. VertexShuriKenParticle.PARTICLE_STARTSIZE = 8;
  16261. VertexShuriKenParticle.PARTICLE_STARTROTATION = 9;
  16262. VertexShuriKenParticle.PARTICLE_STARTSPEED = 10;
  16263. VertexShuriKenParticle.PARTICLE_RANDOM0 = 11;
  16264. VertexShuriKenParticle.PARTICLE_RANDOM1 = 12;
  16265. VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION = 13;
  16266. VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION = 14;
  16267. class VertexShurikenParticleBillboard extends VertexShuriKenParticle {
  16268. static get vertexDeclaration() {
  16269. return VertexShurikenParticleBillboard._vertexDeclaration;
  16270. }
  16271. static __init__() {
  16272. VertexShurikenParticleBillboard._vertexDeclaration = new VertexDeclaration(152, [new VertexElement(0, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0),
  16273. new VertexElement(16, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME),
  16274. new VertexElement(32, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_DIRECTIONTIME),
  16275. new VertexElement(48, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_STARTCOLOR0),
  16276. new VertexElement(64, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTSIZE),
  16277. new VertexElement(76, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTROTATION),
  16278. new VertexElement(88, VertexElementFormat.Single, VertexShuriKenParticle.PARTICLE_STARTSPEED),
  16279. new VertexElement(92, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM0),
  16280. new VertexElement(108, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM1),
  16281. new VertexElement(124, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION),
  16282. new VertexElement(136, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION)]);
  16283. }
  16284. get cornerTextureCoordinate() {
  16285. return this._cornerTextureCoordinate;
  16286. }
  16287. get positionStartLifeTime() {
  16288. return this._positionStartLifeTime;
  16289. }
  16290. get velocity() {
  16291. return this._velocity;
  16292. }
  16293. get startColor() {
  16294. return this._startColor;
  16295. }
  16296. get startSize() {
  16297. return this._startSize;
  16298. }
  16299. get startRotation0() {
  16300. return this._startRotation0;
  16301. }
  16302. get startRotation1() {
  16303. return this._startRotation1;
  16304. }
  16305. get startRotation2() {
  16306. return this._startRotation2;
  16307. }
  16308. get startLifeTime() {
  16309. return this._startLifeTime;
  16310. }
  16311. get time() {
  16312. return this._time;
  16313. }
  16314. get startSpeed() {
  16315. return this._startSpeed;
  16316. }
  16317. get random0() {
  16318. return this._randoms0;
  16319. }
  16320. get random1() {
  16321. return this._randoms1;
  16322. }
  16323. get simulationWorldPostion() {
  16324. return this._simulationWorldPostion;
  16325. }
  16326. constructor(cornerTextureCoordinate, positionStartLifeTime, velocity, startColor, startSize, startRotation0, startRotation1, startRotation2, ageAddScale, time, startSpeed, randoms0, randoms1, simulationWorldPostion) {
  16327. super();
  16328. this._cornerTextureCoordinate = cornerTextureCoordinate;
  16329. this._positionStartLifeTime = positionStartLifeTime;
  16330. this._velocity = velocity;
  16331. this._startColor = startColor;
  16332. this._startSize = startSize;
  16333. this._startRotation0 = startRotation0;
  16334. this._startRotation1 = startRotation1;
  16335. this._startRotation2 = startRotation2;
  16336. this._startLifeTime = ageAddScale;
  16337. this._time = time;
  16338. this._startSpeed = startSpeed;
  16339. this._randoms0 = this.random0;
  16340. this._randoms1 = this.random1;
  16341. this._simulationWorldPostion = simulationWorldPostion;
  16342. }
  16343. }
  16344. class VertexShurikenParticleMesh extends VertexShuriKenParticle {
  16345. static __init__() {
  16346. VertexShurikenParticleMesh._vertexDeclaration = new VertexDeclaration(172, [new VertexElement(0, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_POSITION0),
  16347. new VertexElement(12, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_COLOR0),
  16348. new VertexElement(28, VertexElementFormat.Vector2, VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0),
  16349. new VertexElement(36, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME),
  16350. new VertexElement(52, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_DIRECTIONTIME),
  16351. new VertexElement(68, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_STARTCOLOR0),
  16352. new VertexElement(84, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTSIZE),
  16353. new VertexElement(96, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTROTATION),
  16354. new VertexElement(108, VertexElementFormat.Single, VertexShuriKenParticle.PARTICLE_STARTSPEED),
  16355. new VertexElement(112, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM0),
  16356. new VertexElement(128, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM1),
  16357. new VertexElement(144, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION),
  16358. new VertexElement(156, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION)]);
  16359. }
  16360. static get vertexDeclaration() {
  16361. return VertexShurikenParticleMesh._vertexDeclaration;
  16362. }
  16363. get cornerTextureCoordinate() {
  16364. return this._cornerTextureCoordinate;
  16365. }
  16366. get position() {
  16367. return this._positionStartLifeTime;
  16368. }
  16369. get velocity() {
  16370. return this._velocity;
  16371. }
  16372. get startColor() {
  16373. return this._startColor;
  16374. }
  16375. get startSize() {
  16376. return this._startSize;
  16377. }
  16378. get startRotation0() {
  16379. return this._startRotation0;
  16380. }
  16381. get startRotation1() {
  16382. return this._startRotation1;
  16383. }
  16384. get startRotation2() {
  16385. return this._startRotation2;
  16386. }
  16387. get startLifeTime() {
  16388. return this._startLifeTime;
  16389. }
  16390. get time() {
  16391. return this._time;
  16392. }
  16393. get startSpeed() {
  16394. return this._startSpeed;
  16395. }
  16396. get random0() {
  16397. return this._randoms0;
  16398. }
  16399. get random1() {
  16400. return this._randoms1;
  16401. }
  16402. get simulationWorldPostion() {
  16403. return this._simulationWorldPostion;
  16404. }
  16405. constructor(cornerTextureCoordinate, positionStartLifeTime, velocity, startColor, startSize, startRotation0, startRotation1, startRotation2, ageAddScale, time, startSpeed, randoms0, randoms1, simulationWorldPostion) {
  16406. super();
  16407. this._cornerTextureCoordinate = cornerTextureCoordinate;
  16408. this._positionStartLifeTime = positionStartLifeTime;
  16409. this._velocity = velocity;
  16410. this._startColor = startColor;
  16411. this._startSize = startSize;
  16412. this._startRotation0 = startRotation0;
  16413. this._startRotation1 = startRotation1;
  16414. this._startRotation2 = startRotation2;
  16415. this._startLifeTime = ageAddScale;
  16416. this._time = time;
  16417. this._startSpeed = startSpeed;
  16418. this._randoms0 = this.random0;
  16419. this._randoms1 = this.random1;
  16420. this._simulationWorldPostion = simulationWorldPostion;
  16421. }
  16422. }
  16423. class BoundSphere {
  16424. constructor(center, radius) {
  16425. this.center = center;
  16426. this.radius = radius;
  16427. }
  16428. toDefault() {
  16429. this.center.toDefault();
  16430. this.radius = 0;
  16431. }
  16432. static createFromSubPoints(points, start, count, out) {
  16433. if (points == null) {
  16434. throw new Error("points");
  16435. }
  16436. if (start < 0 || start >= points.length) {
  16437. throw new Error("start" + start + "Must be in the range [0, " + (points.length - 1) + "]");
  16438. }
  16439. if (count < 0 || (start + count) > points.length) {
  16440. throw new Error("count" + count + "Must be in the range <= " + points.length + "}");
  16441. }
  16442. var upperEnd = start + count;
  16443. var center = BoundSphere._tempVector3;
  16444. center.x = 0;
  16445. center.y = 0;
  16446. center.z = 0;
  16447. for (var i = start; i < upperEnd; ++i) {
  16448. Vector3.add(points[i], center, center);
  16449. }
  16450. var outCenter = out.center;
  16451. Vector3.scale(center, 1 / count, outCenter);
  16452. var radius = 0.0;
  16453. for (i = start; i < upperEnd; ++i) {
  16454. var distance = Vector3.distanceSquared(outCenter, points[i]);
  16455. if (distance > radius)
  16456. radius = distance;
  16457. }
  16458. out.radius = Math.sqrt(radius);
  16459. }
  16460. static createfromPoints(points, out) {
  16461. if (points == null) {
  16462. throw new Error("points");
  16463. }
  16464. BoundSphere.createFromSubPoints(points, 0, points.length, out);
  16465. }
  16466. intersectsRayDistance(ray) {
  16467. return CollisionUtils.intersectsRayAndSphereRD(ray, this);
  16468. }
  16469. intersectsRayPoint(ray, outPoint) {
  16470. return CollisionUtils.intersectsRayAndSphereRP(ray, this, outPoint);
  16471. }
  16472. cloneTo(destObject) {
  16473. var dest = destObject;
  16474. this.center.cloneTo(dest.center);
  16475. dest.radius = this.radius;
  16476. }
  16477. clone() {
  16478. var dest = new BoundSphere(new Vector3(), 0);
  16479. this.cloneTo(dest);
  16480. return dest;
  16481. }
  16482. }
  16483. BoundSphere._tempVector3 = new Vector3();
  16484. class Rand {
  16485. constructor(seed) {
  16486. this._temp = new Uint32Array(1);
  16487. this.seeds = new Uint32Array(4);
  16488. this.seeds[0] = seed;
  16489. this.seeds[1] = this.seeds[0] * 0x6C078965 + 1;
  16490. this.seeds[2] = this.seeds[1] * 0x6C078965 + 1;
  16491. this.seeds[3] = this.seeds[2] * 0x6C078965 + 1;
  16492. }
  16493. static getFloatFromInt(v) {
  16494. return (v & 0x007FFFFF) * (1.0 / 8388607.0);
  16495. }
  16496. static getByteFromInt(v) {
  16497. return (v & 0x007FFFFF) >>> 15;
  16498. }
  16499. get seed() {
  16500. return this.seeds[0];
  16501. }
  16502. set seed(seed) {
  16503. this.seeds[0] = seed;
  16504. this.seeds[1] = this.seeds[0] * 0x6C078965 + 1;
  16505. this.seeds[2] = this.seeds[1] * 0x6C078965 + 1;
  16506. this.seeds[3] = this.seeds[2] * 0x6C078965 + 1;
  16507. }
  16508. getUint() {
  16509. this._temp[0] = this.seeds[0] ^ (this.seeds[0] << 11);
  16510. this.seeds[0] = this.seeds[1];
  16511. this.seeds[1] = this.seeds[2];
  16512. this.seeds[2] = this.seeds[3];
  16513. this.seeds[3] = (this.seeds[3] ^ (this.seeds[3] >>> 19)) ^ (this._temp[0] ^ (this._temp[0] >>> 8));
  16514. return this.seeds[3];
  16515. }
  16516. getFloat() {
  16517. this.getUint();
  16518. return (this.seeds[3] & 0x007FFFFF) * (1.0 / 8388607.0);
  16519. }
  16520. getSignedFloat() {
  16521. return this.getFloat() * 2.0 - 1.0;
  16522. }
  16523. }
  16524. class Emission {
  16525. set emissionRate(value) {
  16526. if (value < 0)
  16527. throw new Error("ParticleBaseShape:emissionRate value must large or equal than 0.");
  16528. this._emissionRate = value;
  16529. }
  16530. get emissionRate() {
  16531. return this._emissionRate;
  16532. }
  16533. get destroyed() {
  16534. return this._destroyed;
  16535. }
  16536. constructor() {
  16537. this._destroyed = false;
  16538. this.emissionRate = 10;
  16539. this._bursts = [];
  16540. }
  16541. destroy() {
  16542. this._bursts = null;
  16543. this._destroyed = true;
  16544. }
  16545. getBurstsCount() {
  16546. return this._bursts.length;
  16547. }
  16548. getBurstByIndex(index) {
  16549. return this._bursts[index];
  16550. }
  16551. addBurst(burst) {
  16552. var burstsCount = this._bursts.length;
  16553. if (burstsCount > 0)
  16554. for (var i = 0; i < burstsCount; i++) {
  16555. if (this._bursts[i].time > burst.time)
  16556. this._bursts.splice(i, 0, burst);
  16557. }
  16558. this._bursts.push(burst);
  16559. }
  16560. removeBurst(burst) {
  16561. var index = this._bursts.indexOf(burst);
  16562. if (index !== -1) {
  16563. this._bursts.splice(index, 1);
  16564. }
  16565. }
  16566. removeBurstByIndex(index) {
  16567. this._bursts.splice(index, 1);
  16568. }
  16569. clearBurst() {
  16570. this._bursts.length = 0;
  16571. }
  16572. cloneTo(destObject) {
  16573. var destEmission = destObject;
  16574. var destBursts = destEmission._bursts;
  16575. destBursts.length = this._bursts.length;
  16576. for (var i = 0, n = this._bursts.length; i < n; i++) {
  16577. var destBurst = destBursts[i];
  16578. if (destBurst)
  16579. this._bursts[i].cloneTo(destBurst);
  16580. else
  16581. destBursts[i] = this._bursts[i].clone();
  16582. }
  16583. destEmission._emissionRate = this._emissionRate;
  16584. destEmission.enbale = this.enbale;
  16585. }
  16586. clone() {
  16587. var destEmission = new Emission();
  16588. this.cloneTo(destEmission);
  16589. return destEmission;
  16590. }
  16591. }
  16592. class GradientDataNumber {
  16593. constructor() {
  16594. this._currentLength = 0;
  16595. this._elements = new Float32Array(8);
  16596. }
  16597. get gradientCount() {
  16598. return this._currentLength / 2;
  16599. }
  16600. add(key, value) {
  16601. if (this._currentLength < 8) {
  16602. if ((this._currentLength === 6) && ((key !== 1))) {
  16603. key = 1;
  16604. console.log("GradientDataNumber warning:the forth key is be force set to 1.");
  16605. }
  16606. this._elements[this._currentLength++] = key;
  16607. this._elements[this._currentLength++] = value;
  16608. }
  16609. else {
  16610. console.log("GradientDataNumber warning:data count must lessEqual than 4");
  16611. }
  16612. }
  16613. getKeyByIndex(index) {
  16614. return this._elements[index * 2];
  16615. }
  16616. getValueByIndex(index) {
  16617. return this._elements[index * 2 + 1];
  16618. }
  16619. getAverageValue() {
  16620. var total = 0;
  16621. for (var i = 0, n = this._currentLength - 2; i < n; i += 2) {
  16622. var subValue = this._elements[i + 1];
  16623. subValue += this._elements[i + 3];
  16624. subValue = subValue * (this._elements[i + 2] - this._elements[i]);
  16625. }
  16626. return total / 2;
  16627. }
  16628. cloneTo(destObject) {
  16629. var destGradientDataNumber = destObject;
  16630. destGradientDataNumber._currentLength = this._currentLength;
  16631. var destElements = destGradientDataNumber._elements;
  16632. for (var i = 0, n = this._elements.length; i < n; i++)
  16633. destElements[i] = this._elements[i];
  16634. }
  16635. clone() {
  16636. var destGradientDataNumber = new GradientDataNumber();
  16637. this.cloneTo(destGradientDataNumber);
  16638. return destGradientDataNumber;
  16639. }
  16640. }
  16641. class ShurikenParticleData {
  16642. constructor() {
  16643. }
  16644. static _getStartLifetimeFromGradient(startLifeTimeGradient, emissionTime) {
  16645. for (var i = 1, n = startLifeTimeGradient.gradientCount; i < n; i++) {
  16646. var key = startLifeTimeGradient.getKeyByIndex(i);
  16647. if (key >= emissionTime) {
  16648. var lastKey = startLifeTimeGradient.getKeyByIndex(i - 1);
  16649. var age = (emissionTime - lastKey) / (key - lastKey);
  16650. return Laya.MathUtil.lerp(startLifeTimeGradient.getValueByIndex(i - 1), startLifeTimeGradient.getValueByIndex(i), age);
  16651. }
  16652. }
  16653. throw new Error("ShurikenParticleData: can't get value foam startLifeTimeGradient.");
  16654. }
  16655. static _randomInvertRoationArray(rotatonE, outE, randomizeRotationDirection, rand, randomSeeds) {
  16656. var randDic;
  16657. if (rand) {
  16658. rand.seed = randomSeeds[6];
  16659. randDic = rand.getFloat();
  16660. randomSeeds[6] = rand.seed;
  16661. }
  16662. else {
  16663. randDic = Math.random();
  16664. }
  16665. if (randDic < randomizeRotationDirection) {
  16666. outE.x = -rotatonE.x;
  16667. outE.y = -rotatonE.y;
  16668. outE.z = -rotatonE.z;
  16669. }
  16670. else {
  16671. outE.x = rotatonE.x;
  16672. outE.y = rotatonE.y;
  16673. outE.z = rotatonE.z;
  16674. }
  16675. }
  16676. static _randomInvertRoation(rotaton, randomizeRotationDirection, rand, randomSeeds) {
  16677. var randDic;
  16678. if (rand) {
  16679. rand.seed = randomSeeds[6];
  16680. randDic = rand.getFloat();
  16681. randomSeeds[6] = rand.seed;
  16682. }
  16683. else {
  16684. randDic = Math.random();
  16685. }
  16686. if (randDic < randomizeRotationDirection)
  16687. rotaton = -rotaton;
  16688. return rotaton;
  16689. }
  16690. static create(particleSystem, particleRender, transform) {
  16691. var autoRandomSeed = particleSystem.autoRandomSeed;
  16692. var rand = particleSystem._rand;
  16693. var randomSeeds = particleSystem._randomSeeds;
  16694. switch (particleSystem.startColorType) {
  16695. case 0:
  16696. var constantStartColor = particleSystem.startColorConstant;
  16697. ShurikenParticleData.startColor.x = constantStartColor.x;
  16698. ShurikenParticleData.startColor.y = constantStartColor.y;
  16699. ShurikenParticleData.startColor.z = constantStartColor.z;
  16700. ShurikenParticleData.startColor.w = constantStartColor.w;
  16701. break;
  16702. case 2:
  16703. if (autoRandomSeed) {
  16704. Vector4.lerp(particleSystem.startColorConstantMin, particleSystem.startColorConstantMax, Math.random(), ShurikenParticleData.startColor);
  16705. }
  16706. else {
  16707. rand.seed = randomSeeds[3];
  16708. Vector4.lerp(particleSystem.startColorConstantMin, particleSystem.startColorConstantMax, rand.getFloat(), ShurikenParticleData.startColor);
  16709. randomSeeds[3] = rand.seed;
  16710. }
  16711. break;
  16712. }
  16713. var colorOverLifetime = particleSystem.colorOverLifetime;
  16714. if (colorOverLifetime && colorOverLifetime.enbale) {
  16715. var color = colorOverLifetime.color;
  16716. switch (color.type) {
  16717. case 0:
  16718. ShurikenParticleData.startColor.x = ShurikenParticleData.startColor.x * color.constant.x;
  16719. ShurikenParticleData.startColor.y = ShurikenParticleData.startColor.y * color.constant.y;
  16720. ShurikenParticleData.startColor.z = ShurikenParticleData.startColor.z * color.constant.z;
  16721. ShurikenParticleData.startColor.w = ShurikenParticleData.startColor.w * color.constant.w;
  16722. break;
  16723. case 2:
  16724. var colorRandom;
  16725. if (autoRandomSeed) {
  16726. colorRandom = Math.random();
  16727. }
  16728. else {
  16729. rand.seed = randomSeeds[10];
  16730. colorRandom = rand.getFloat();
  16731. randomSeeds[10] = rand.seed;
  16732. }
  16733. var minConstantColor = color.constantMin;
  16734. var maxConstantColor = color.constantMax;
  16735. ShurikenParticleData.startColor.x = ShurikenParticleData.startColor.x * Laya.MathUtil.lerp(minConstantColor.x, maxConstantColor.x, colorRandom);
  16736. ShurikenParticleData.startColor.y = ShurikenParticleData.startColor.y * Laya.MathUtil.lerp(minConstantColor.y, maxConstantColor.y, colorRandom);
  16737. ShurikenParticleData.startColor.z = ShurikenParticleData.startColor.z * Laya.MathUtil.lerp(minConstantColor.z, maxConstantColor.z, colorRandom);
  16738. ShurikenParticleData.startColor.w = ShurikenParticleData.startColor.w * Laya.MathUtil.lerp(minConstantColor.w, maxConstantColor.w, colorRandom);
  16739. break;
  16740. }
  16741. }
  16742. var particleSize = ShurikenParticleData.startSize;
  16743. switch (particleSystem.startSizeType) {
  16744. case 0:
  16745. if (particleSystem.threeDStartSize) {
  16746. var startSizeConstantSeparate = particleSystem.startSizeConstantSeparate;
  16747. particleSize[0] = startSizeConstantSeparate.x;
  16748. particleSize[1] = startSizeConstantSeparate.y;
  16749. particleSize[2] = startSizeConstantSeparate.z;
  16750. }
  16751. else {
  16752. particleSize[0] = particleSize[1] = particleSize[2] = particleSystem.startSizeConstant;
  16753. }
  16754. break;
  16755. case 2:
  16756. if (particleSystem.threeDStartSize) {
  16757. var startSizeConstantMinSeparate = particleSystem.startSizeConstantMinSeparate;
  16758. var startSizeConstantMaxSeparate = particleSystem.startSizeConstantMaxSeparate;
  16759. if (autoRandomSeed) {
  16760. particleSize[0] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.x, startSizeConstantMaxSeparate.x, Math.random());
  16761. particleSize[1] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.y, startSizeConstantMaxSeparate.y, Math.random());
  16762. particleSize[2] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.z, startSizeConstantMaxSeparate.z, Math.random());
  16763. }
  16764. else {
  16765. rand.seed = randomSeeds[4];
  16766. particleSize[0] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.x, startSizeConstantMaxSeparate.x, rand.getFloat());
  16767. particleSize[1] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.y, startSizeConstantMaxSeparate.y, rand.getFloat());
  16768. particleSize[2] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.z, startSizeConstantMaxSeparate.z, rand.getFloat());
  16769. randomSeeds[4] = rand.seed;
  16770. }
  16771. }
  16772. else {
  16773. if (autoRandomSeed) {
  16774. particleSize[0] = particleSize[1] = particleSize[2] = Laya.MathUtil.lerp(particleSystem.startSizeConstantMin, particleSystem.startSizeConstantMax, Math.random());
  16775. }
  16776. else {
  16777. rand.seed = randomSeeds[4];
  16778. particleSize[0] = particleSize[1] = particleSize[2] = Laya.MathUtil.lerp(particleSystem.startSizeConstantMin, particleSystem.startSizeConstantMax, rand.getFloat());
  16779. randomSeeds[4] = rand.seed;
  16780. }
  16781. }
  16782. break;
  16783. }
  16784. var sizeOverLifetime = particleSystem.sizeOverLifetime;
  16785. if (sizeOverLifetime && sizeOverLifetime.enbale && sizeOverLifetime.size.type === 1) {
  16786. var size = sizeOverLifetime.size;
  16787. if (size.separateAxes) {
  16788. if (autoRandomSeed) {
  16789. particleSize[0] = particleSize[0] * Laya.MathUtil.lerp(size.constantMinSeparate.x, size.constantMaxSeparate.x, Math.random());
  16790. particleSize[1] = particleSize[1] * Laya.MathUtil.lerp(size.constantMinSeparate.y, size.constantMaxSeparate.y, Math.random());
  16791. particleSize[2] = particleSize[2] * Laya.MathUtil.lerp(size.constantMinSeparate.z, size.constantMaxSeparate.z, Math.random());
  16792. }
  16793. else {
  16794. rand.seed = randomSeeds[11];
  16795. particleSize[0] = particleSize[0] * Laya.MathUtil.lerp(size.constantMinSeparate.x, size.constantMaxSeparate.x, rand.getFloat());
  16796. particleSize[1] = particleSize[1] * Laya.MathUtil.lerp(size.constantMinSeparate.y, size.constantMaxSeparate.y, rand.getFloat());
  16797. particleSize[2] = particleSize[2] * Laya.MathUtil.lerp(size.constantMinSeparate.z, size.constantMaxSeparate.z, rand.getFloat());
  16798. randomSeeds[11] = rand.seed;
  16799. }
  16800. }
  16801. else {
  16802. var randomSize;
  16803. if (autoRandomSeed) {
  16804. randomSize = Laya.MathUtil.lerp(size.constantMin, size.constantMax, Math.random());
  16805. }
  16806. else {
  16807. rand.seed = randomSeeds[11];
  16808. randomSize = Laya.MathUtil.lerp(size.constantMin, size.constantMax, rand.getFloat());
  16809. randomSeeds[11] = rand.seed;
  16810. }
  16811. particleSize[0] = particleSize[0] * randomSize;
  16812. particleSize[1] = particleSize[1] * randomSize;
  16813. particleSize[2] = particleSize[2] * randomSize;
  16814. }
  16815. }
  16816. var renderMode = particleRender.renderMode;
  16817. if (renderMode !== 1) {
  16818. switch (particleSystem.startRotationType) {
  16819. case 0:
  16820. if (particleSystem.threeDStartRotation) {
  16821. var startRotationConstantSeparate = particleSystem.startRotationConstantSeparate;
  16822. var randomRotationE = ShurikenParticleData._tempVector30;
  16823. ShurikenParticleData._randomInvertRoationArray(startRotationConstantSeparate, randomRotationE, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  16824. ShurikenParticleData.startRotation[0] = randomRotationE.x;
  16825. ShurikenParticleData.startRotation[1] = randomRotationE.y;
  16826. if (renderMode !== 4)
  16827. ShurikenParticleData.startRotation[2] = -randomRotationE.z;
  16828. else
  16829. ShurikenParticleData.startRotation[2] = randomRotationE.z;
  16830. }
  16831. else {
  16832. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(particleSystem.startRotationConstant, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  16833. ShurikenParticleData.startRotation[1] = 0;
  16834. ShurikenParticleData.startRotation[2] = 0;
  16835. }
  16836. break;
  16837. case 2:
  16838. if (particleSystem.threeDStartRotation) {
  16839. var startRotationConstantMinSeparate = particleSystem.startRotationConstantMinSeparate;
  16840. var startRotationConstantMaxSeparate = particleSystem.startRotationConstantMaxSeparate;
  16841. var lerpRoationE = ShurikenParticleData._tempVector30;
  16842. if (autoRandomSeed) {
  16843. lerpRoationE.x = Laya.MathUtil.lerp(startRotationConstantMinSeparate.x, startRotationConstantMaxSeparate.x, Math.random());
  16844. lerpRoationE.y = Laya.MathUtil.lerp(startRotationConstantMinSeparate.y, startRotationConstantMaxSeparate.y, Math.random());
  16845. lerpRoationE.z = Laya.MathUtil.lerp(startRotationConstantMinSeparate.z, startRotationConstantMaxSeparate.z, Math.random());
  16846. }
  16847. else {
  16848. rand.seed = randomSeeds[5];
  16849. lerpRoationE.x = Laya.MathUtil.lerp(startRotationConstantMinSeparate.x, startRotationConstantMaxSeparate.x, rand.getFloat());
  16850. lerpRoationE.y = Laya.MathUtil.lerp(startRotationConstantMinSeparate.y, startRotationConstantMaxSeparate.y, rand.getFloat());
  16851. lerpRoationE.z = Laya.MathUtil.lerp(startRotationConstantMinSeparate.z, startRotationConstantMaxSeparate.z, rand.getFloat());
  16852. randomSeeds[5] = rand.seed;
  16853. }
  16854. ShurikenParticleData._randomInvertRoationArray(lerpRoationE, lerpRoationE, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  16855. ShurikenParticleData.startRotation[0] = lerpRoationE.x;
  16856. ShurikenParticleData.startRotation[1] = lerpRoationE.y;
  16857. if (renderMode !== 4)
  16858. ShurikenParticleData.startRotation[2] = -lerpRoationE.z;
  16859. else
  16860. ShurikenParticleData.startRotation[2] = lerpRoationE.z;
  16861. }
  16862. else {
  16863. if (autoRandomSeed) {
  16864. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(Laya.MathUtil.lerp(particleSystem.startRotationConstantMin, particleSystem.startRotationConstantMax, Math.random()), particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  16865. }
  16866. else {
  16867. rand.seed = randomSeeds[5];
  16868. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(Laya.MathUtil.lerp(particleSystem.startRotationConstantMin, particleSystem.startRotationConstantMax, rand.getFloat()), particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  16869. randomSeeds[5] = rand.seed;
  16870. }
  16871. }
  16872. break;
  16873. }
  16874. }
  16875. switch (particleSystem.startLifetimeType) {
  16876. case 0:
  16877. ShurikenParticleData.startLifeTime = particleSystem.startLifetimeConstant;
  16878. break;
  16879. case 1:
  16880. ShurikenParticleData.startLifeTime = ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradient, particleSystem.emissionTime);
  16881. break;
  16882. case 2:
  16883. if (autoRandomSeed) {
  16884. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(particleSystem.startLifetimeConstantMin, particleSystem.startLifetimeConstantMax, Math.random());
  16885. }
  16886. else {
  16887. rand.seed = randomSeeds[7];
  16888. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(particleSystem.startLifetimeConstantMin, particleSystem.startLifetimeConstantMax, rand.getFloat());
  16889. randomSeeds[7] = rand.seed;
  16890. }
  16891. break;
  16892. case 3:
  16893. var emissionTime = particleSystem.emissionTime;
  16894. if (autoRandomSeed) {
  16895. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin, emissionTime), ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax, emissionTime), Math.random());
  16896. }
  16897. else {
  16898. rand.seed = randomSeeds[7];
  16899. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin, emissionTime), ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax, emissionTime), rand.getFloat());
  16900. randomSeeds[7] = rand.seed;
  16901. }
  16902. break;
  16903. }
  16904. var textureSheetAnimation = particleSystem.textureSheetAnimation;
  16905. var enableSheetAnimation = textureSheetAnimation && textureSheetAnimation.enable;
  16906. if (enableSheetAnimation) {
  16907. var title = textureSheetAnimation.tiles;
  16908. var titleX = title.x, titleY = title.y;
  16909. var subU = 1.0 / titleX, subV = 1.0 / titleY;
  16910. var startFrameCount;
  16911. var startFrame = textureSheetAnimation.startFrame;
  16912. switch (startFrame.type) {
  16913. case 0:
  16914. startFrameCount = startFrame.constant;
  16915. break;
  16916. case 1:
  16917. if (autoRandomSeed) {
  16918. startFrameCount = Laya.MathUtil.lerp(startFrame.constantMin, startFrame.constantMax, Math.random());
  16919. }
  16920. else {
  16921. rand.seed = randomSeeds[14];
  16922. startFrameCount = Laya.MathUtil.lerp(startFrame.constantMin, startFrame.constantMax, rand.getFloat());
  16923. randomSeeds[14] = rand.seed;
  16924. }
  16925. break;
  16926. }
  16927. var frame = textureSheetAnimation.frame;
  16928. var cycles = textureSheetAnimation.cycles;
  16929. switch (frame.type) {
  16930. case 0:
  16931. startFrameCount += frame.constant * cycles;
  16932. break;
  16933. case 2:
  16934. if (autoRandomSeed) {
  16935. startFrameCount += Laya.MathUtil.lerp(frame.constantMin, frame.constantMax, Math.random()) * cycles;
  16936. }
  16937. else {
  16938. rand.seed = randomSeeds[15];
  16939. startFrameCount += Laya.MathUtil.lerp(frame.constantMin, frame.constantMax, rand.getFloat()) * cycles;
  16940. randomSeeds[15] = rand.seed;
  16941. }
  16942. break;
  16943. }
  16944. var startRow = 0;
  16945. switch (textureSheetAnimation.type) {
  16946. case 0:
  16947. startRow = Math.floor(startFrameCount / titleX);
  16948. break;
  16949. case 1:
  16950. if (textureSheetAnimation.randomRow) {
  16951. if (autoRandomSeed) {
  16952. startRow = Math.floor(Math.random() * titleY);
  16953. }
  16954. else {
  16955. rand.seed = randomSeeds[13];
  16956. startRow = Math.floor(rand.getFloat() * titleY);
  16957. randomSeeds[13] = rand.seed;
  16958. }
  16959. }
  16960. else {
  16961. startRow = textureSheetAnimation.rowIndex;
  16962. }
  16963. break;
  16964. }
  16965. var startCol = Math.floor(startFrameCount % titleX);
  16966. ShurikenParticleData.startUVInfo = ShurikenParticleData.startUVInfo;
  16967. ShurikenParticleData.startUVInfo[0] = subU;
  16968. ShurikenParticleData.startUVInfo[1] = subV;
  16969. ShurikenParticleData.startUVInfo[2] = startCol * subU;
  16970. ShurikenParticleData.startUVInfo[3] = startRow * subV;
  16971. }
  16972. else {
  16973. ShurikenParticleData.startUVInfo = ShurikenParticleData.startUVInfo;
  16974. ShurikenParticleData.startUVInfo[0] = 1.0;
  16975. ShurikenParticleData.startUVInfo[1] = 1.0;
  16976. ShurikenParticleData.startUVInfo[2] = 0.0;
  16977. ShurikenParticleData.startUVInfo[3] = 0.0;
  16978. }
  16979. }
  16980. }
  16981. ShurikenParticleData._tempVector30 = new Vector3();
  16982. ShurikenParticleData.startColor = new Vector4();
  16983. ShurikenParticleData.startSize = new Float32Array(3);
  16984. ShurikenParticleData.startRotation = new Float32Array(3);
  16985. ShurikenParticleData.startUVInfo = new Float32Array(4);
  16986. class ShurikenParticleSystem extends GeometryElement {
  16987. constructor(owner) {
  16988. super();
  16989. this._tempRotationMatrix = new Matrix4x4();
  16990. this._boundingSphere = null;
  16991. this._boundingBox = null;
  16992. this._boundingBoxCorners = null;
  16993. this._owner = null;
  16994. this._ownerRender = null;
  16995. this._vertices = null;
  16996. this._floatCountPerVertex = 0;
  16997. this._startLifeTimeIndex = 0;
  16998. this._timeIndex = 0;
  16999. this._simulateUpdate = false;
  17000. this._firstActiveElement = 0;
  17001. this._firstNewElement = 0;
  17002. this._firstFreeElement = 0;
  17003. this._firstRetiredElement = 0;
  17004. this._drawCounter = 0;
  17005. this._bufferMaxParticles = 0;
  17006. this._emission = null;
  17007. this._shape = null;
  17008. this._isEmitting = false;
  17009. this._isPlaying = false;
  17010. this._isPaused = false;
  17011. this._playStartDelay = 0;
  17012. this._frameRateTime = 0;
  17013. this._emissionTime = 0;
  17014. this._totalDelayTime = 0;
  17015. this._burstsIndex = 0;
  17016. this._velocityOverLifetime = null;
  17017. this._colorOverLifetime = null;
  17018. this._sizeOverLifetime = null;
  17019. this._rotationOverLifetime = null;
  17020. this._textureSheetAnimation = null;
  17021. this._startLifetimeType = 0;
  17022. this._startLifetimeConstant = 0;
  17023. this._startLifeTimeGradient = null;
  17024. this._startLifetimeConstantMin = 0;
  17025. this._startLifetimeConstantMax = 0;
  17026. this._startLifeTimeGradientMin = null;
  17027. this._startLifeTimeGradientMax = null;
  17028. this._maxStartLifetime = 0;
  17029. this._uvLength = new Vector2();
  17030. this._vertexStride = 0;
  17031. this._indexStride = 0;
  17032. this._vertexBuffer = null;
  17033. this._indexBuffer = null;
  17034. this._bufferState = new BufferState();
  17035. this._currentTime = 0;
  17036. this._startUpdateLoopCount = 0;
  17037. this._rand = null;
  17038. this._randomSeeds = null;
  17039. this.duration = 0;
  17040. this.looping = false;
  17041. this.prewarm = false;
  17042. this.startDelayType = 0;
  17043. this.startDelay = 0;
  17044. this.startDelayMin = 0;
  17045. this.startDelayMax = 0;
  17046. this.startSpeedType = 0;
  17047. this.startSpeedConstant = 0;
  17048. this.startSpeedConstantMin = 0;
  17049. this.startSpeedConstantMax = 0;
  17050. this.threeDStartSize = false;
  17051. this.startSizeType = 0;
  17052. this.startSizeConstant = 0;
  17053. this.startSizeConstantSeparate = null;
  17054. this.startSizeConstantMin = 0;
  17055. this.startSizeConstantMax = 0;
  17056. this.startSizeConstantMinSeparate = null;
  17057. this.startSizeConstantMaxSeparate = null;
  17058. this.threeDStartRotation = false;
  17059. this.startRotationType = 0;
  17060. this.startRotationConstant = 0;
  17061. this.startRotationConstantSeparate = null;
  17062. this.startRotationConstantMin = 0;
  17063. this.startRotationConstantMax = 0;
  17064. this.startRotationConstantMinSeparate = null;
  17065. this.startRotationConstantMaxSeparate = null;
  17066. this.randomizeRotationDirection = 0;
  17067. this.startColorType = 0;
  17068. this.startColorConstant = null;
  17069. this.startColorConstantMin = null;
  17070. this.startColorConstantMax = null;
  17071. this.gravityModifier = 0;
  17072. this.simulationSpace = 0;
  17073. this.simulationSpeed = 1.0;
  17074. this.scaleMode = 0;
  17075. this.playOnAwake = false;
  17076. this.randomSeed = null;
  17077. this.autoRandomSeed = false;
  17078. this.isPerformanceMode = false;
  17079. this._firstActiveElement = 0;
  17080. this._firstNewElement = 0;
  17081. this._firstFreeElement = 0;
  17082. this._firstRetiredElement = 0;
  17083. this._owner = owner;
  17084. this._ownerRender = owner.particleRenderer;
  17085. this._boundingBoxCorners = [];
  17086. this._boundingSphere = new BoundSphere(new Vector3(), Number.MAX_VALUE);
  17087. 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));
  17088. this._currentTime = 0;
  17089. this._isEmitting = false;
  17090. this._isPlaying = false;
  17091. this._isPaused = false;
  17092. this._burstsIndex = 0;
  17093. this._frameRateTime = 0;
  17094. this._emissionTime = 0;
  17095. this._totalDelayTime = 0;
  17096. this._simulateUpdate = false;
  17097. this._bufferMaxParticles = 1;
  17098. this.duration = 5.0;
  17099. this.looping = true;
  17100. this.prewarm = false;
  17101. this.startDelayType = 0;
  17102. this.startDelay = 0.0;
  17103. this.startDelayMin = 0.0;
  17104. this.startDelayMax = 0.0;
  17105. this._startLifetimeType = 0;
  17106. this._startLifetimeConstant = 5.0;
  17107. this._startLifeTimeGradient = new GradientDataNumber();
  17108. this._startLifetimeConstantMin = 0.0;
  17109. this._startLifetimeConstantMax = 5.0;
  17110. this._startLifeTimeGradientMin = new GradientDataNumber();
  17111. this._startLifeTimeGradientMax = new GradientDataNumber();
  17112. this._maxStartLifetime = 5.0;
  17113. this.startSpeedType = 0;
  17114. this.startSpeedConstant = 5.0;
  17115. this.startSpeedConstantMin = 0.0;
  17116. this.startSpeedConstantMax = 5.0;
  17117. this.threeDStartSize = false;
  17118. this.startSizeType = 0;
  17119. this.startSizeConstant = 1;
  17120. this.startSizeConstantSeparate = new Vector3(1, 1, 1);
  17121. this.startSizeConstantMin = 0;
  17122. this.startSizeConstantMax = 1;
  17123. this.startSizeConstantMinSeparate = new Vector3(0, 0, 0);
  17124. this.startSizeConstantMaxSeparate = new Vector3(1, 1, 1);
  17125. this.threeDStartRotation = false;
  17126. this.startRotationType = 0;
  17127. this.startRotationConstant = 0;
  17128. this.startRotationConstantSeparate = new Vector3(0, 0, 0);
  17129. this.startRotationConstantMin = 0.0;
  17130. this.startRotationConstantMax = 0.0;
  17131. this.startRotationConstantMinSeparate = new Vector3(0, 0, 0);
  17132. this.startRotationConstantMaxSeparate = new Vector3(0, 0, 0);
  17133. this.randomizeRotationDirection = 0.0;
  17134. this.startColorType = 0;
  17135. this.startColorConstant = new Vector4(1, 1, 1, 1);
  17136. this.startColorConstantMin = new Vector4(1, 1, 1, 1);
  17137. this.startColorConstantMax = new Vector4(1, 1, 1, 1);
  17138. this.gravityModifier = 0.0;
  17139. this.simulationSpace = 1;
  17140. this.scaleMode = 0;
  17141. this.playOnAwake = true;
  17142. this._rand = new Rand(0);
  17143. this.autoRandomSeed = true;
  17144. this.randomSeed = new Uint32Array(1);
  17145. this._randomSeeds = new Uint32Array(ShurikenParticleSystem._RANDOMOFFSET.length);
  17146. this.isPerformanceMode = true;
  17147. this._emission = new Emission();
  17148. this._emission.enbale = true;
  17149. }
  17150. get maxParticles() {
  17151. return this._bufferMaxParticles - 1;
  17152. }
  17153. set maxParticles(value) {
  17154. var newMaxParticles = value + 1;
  17155. if (newMaxParticles !== this._bufferMaxParticles) {
  17156. this._bufferMaxParticles = newMaxParticles;
  17157. this._initBufferDatas();
  17158. }
  17159. }
  17160. get emission() {
  17161. return this._emission;
  17162. }
  17163. get aliveParticleCount() {
  17164. if (this._firstNewElement >= this._firstRetiredElement)
  17165. return this._firstNewElement - this._firstRetiredElement;
  17166. else
  17167. return this._bufferMaxParticles - this._firstRetiredElement + this._firstNewElement;
  17168. }
  17169. get emissionTime() {
  17170. return this._emissionTime > this.duration ? this.duration : this._emissionTime;
  17171. }
  17172. get shape() {
  17173. return this._shape;
  17174. }
  17175. set shape(value) {
  17176. if (this._shape !== value) {
  17177. if (value && value.enable)
  17178. this._owner._render._shaderValues.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE);
  17179. else
  17180. this._owner._render._shaderValues.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE);
  17181. this._shape = value;
  17182. }
  17183. }
  17184. get isAlive() {
  17185. if (this._isPlaying || this.aliveParticleCount > 0)
  17186. return true;
  17187. return false;
  17188. }
  17189. get isEmitting() {
  17190. return this._isEmitting;
  17191. }
  17192. get isPlaying() {
  17193. return this._isPlaying;
  17194. }
  17195. get isPaused() {
  17196. return this._isPaused;
  17197. }
  17198. get startLifetimeType() {
  17199. return this._startLifetimeType;
  17200. }
  17201. set startLifetimeType(value) {
  17202. var i, n;
  17203. switch (this.startLifetimeType) {
  17204. case 0:
  17205. this._maxStartLifetime = this.startLifetimeConstant;
  17206. break;
  17207. case 1:
  17208. this._maxStartLifetime = -Number.MAX_VALUE;
  17209. var startLifeTimeGradient = startLifeTimeGradient;
  17210. for (i = 0, n = startLifeTimeGradient.gradientCount; i < n; i++)
  17211. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradient.getValueByIndex(i));
  17212. break;
  17213. case 2:
  17214. this._maxStartLifetime = Math.max(this.startLifetimeConstantMin, this.startLifetimeConstantMax);
  17215. break;
  17216. case 3:
  17217. this._maxStartLifetime = -Number.MAX_VALUE;
  17218. var startLifeTimeGradientMin = startLifeTimeGradientMin;
  17219. for (i = 0, n = startLifeTimeGradientMin.gradientCount; i < n; i++)
  17220. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradientMin.getValueByIndex(i));
  17221. var startLifeTimeGradientMax = startLifeTimeGradientMax;
  17222. for (i = 0, n = startLifeTimeGradientMax.gradientCount; i < n; i++)
  17223. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradientMax.getValueByIndex(i));
  17224. break;
  17225. }
  17226. this._startLifetimeType = value;
  17227. }
  17228. get startLifetimeConstant() {
  17229. return this._startLifetimeConstant;
  17230. }
  17231. set startLifetimeConstant(value) {
  17232. if (this._startLifetimeType === 0)
  17233. this._maxStartLifetime = value;
  17234. this._startLifetimeConstant = value;
  17235. }
  17236. get startLifeTimeGradient() {
  17237. return this._startLifeTimeGradient;
  17238. }
  17239. set startLifeTimeGradient(value) {
  17240. if (this._startLifetimeType === 1) {
  17241. this._maxStartLifetime = -Number.MAX_VALUE;
  17242. for (var i = 0, n = value.gradientCount; i < n; i++)
  17243. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  17244. }
  17245. this._startLifeTimeGradient = value;
  17246. }
  17247. get startLifetimeConstantMin() {
  17248. return this._startLifetimeConstantMin;
  17249. }
  17250. set startLifetimeConstantMin(value) {
  17251. if (this._startLifetimeType === 2)
  17252. this._maxStartLifetime = Math.max(value, this._startLifetimeConstantMax);
  17253. this._startLifetimeConstantMin = value;
  17254. }
  17255. get startLifetimeConstantMax() {
  17256. return this._startLifetimeConstantMax;
  17257. }
  17258. set startLifetimeConstantMax(value) {
  17259. if (this._startLifetimeType === 2)
  17260. this._maxStartLifetime = Math.max(this._startLifetimeConstantMin, value);
  17261. this._startLifetimeConstantMax = value;
  17262. }
  17263. get startLifeTimeGradientMin() {
  17264. return this._startLifeTimeGradientMin;
  17265. }
  17266. set startLifeTimeGradientMin(value) {
  17267. if (this._startLifetimeType === 3) {
  17268. var i, n;
  17269. this._maxStartLifetime = -Number.MAX_VALUE;
  17270. for (i = 0, n = value.gradientCount; i < n; i++)
  17271. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  17272. for (i = 0, n = this._startLifeTimeGradientMax.gradientCount; i < n; i++)
  17273. this._maxStartLifetime = Math.max(this._maxStartLifetime, this._startLifeTimeGradientMax.getValueByIndex(i));
  17274. }
  17275. this._startLifeTimeGradientMin = value;
  17276. }
  17277. get startLifeTimeGradientMax() {
  17278. return this._startLifeTimeGradientMax;
  17279. }
  17280. set startLifeTimeGradientMax(value) {
  17281. if (this._startLifetimeType === 3) {
  17282. var i, n;
  17283. this._maxStartLifetime = -Number.MAX_VALUE;
  17284. for (i = 0, n = this._startLifeTimeGradientMin.gradientCount; i < n; i++)
  17285. this._maxStartLifetime = Math.max(this._maxStartLifetime, this._startLifeTimeGradientMin.getValueByIndex(i));
  17286. for (i = 0, n = value.gradientCount; i < n; i++)
  17287. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  17288. }
  17289. this._startLifeTimeGradientMax = value;
  17290. }
  17291. get velocityOverLifetime() {
  17292. return this._velocityOverLifetime;
  17293. }
  17294. set velocityOverLifetime(value) {
  17295. var shaDat = this._owner._render._shaderValues;
  17296. if (value) {
  17297. var velocity = value.velocity;
  17298. var velocityType = velocity.type;
  17299. if (value.enbale) {
  17300. switch (velocityType) {
  17301. case 0:
  17302. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  17303. break;
  17304. case 1:
  17305. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  17306. break;
  17307. case 2:
  17308. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  17309. break;
  17310. case 3:
  17311. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  17312. break;
  17313. }
  17314. }
  17315. else {
  17316. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  17317. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  17318. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  17319. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  17320. }
  17321. switch (velocityType) {
  17322. case 0:
  17323. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST, velocity.constant);
  17324. break;
  17325. case 1:
  17326. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX, velocity.gradientX._elements);
  17327. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY, velocity.gradientY._elements);
  17328. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ, velocity.gradientZ._elements);
  17329. break;
  17330. case 2:
  17331. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST, velocity.constantMin);
  17332. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONSTMAX, velocity.constantMax);
  17333. break;
  17334. case 3:
  17335. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX, velocity.gradientXMin._elements);
  17336. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTXMAX, velocity.gradientXMax._elements);
  17337. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY, velocity.gradientYMin._elements);
  17338. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTYMAX, velocity.gradientYMax._elements);
  17339. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ, velocity.gradientZMin._elements);
  17340. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZMAX, velocity.gradientZMax._elements);
  17341. break;
  17342. }
  17343. shaDat.setInt(ShuriKenParticle3DShaderDeclaration.VOLSPACETYPE, value.space);
  17344. }
  17345. else {
  17346. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  17347. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  17348. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  17349. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  17350. }
  17351. this._velocityOverLifetime = value;
  17352. }
  17353. get colorOverLifetime() {
  17354. return this._colorOverLifetime;
  17355. }
  17356. set colorOverLifetime(value) {
  17357. var shaDat = this._owner._render._shaderValues;
  17358. if (value) {
  17359. var color = value.color;
  17360. if (value.enbale) {
  17361. switch (color.type) {
  17362. case 1:
  17363. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  17364. break;
  17365. case 3:
  17366. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  17367. break;
  17368. }
  17369. }
  17370. else {
  17371. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  17372. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  17373. }
  17374. switch (color.type) {
  17375. case 1:
  17376. var gradientColor = color.gradient;
  17377. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, gradientColor._alphaElements);
  17378. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, gradientColor._rgbElements);
  17379. break;
  17380. case 3:
  17381. var minGradientColor = color.gradientMin;
  17382. var maxGradientColor = color.gradientMax;
  17383. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, minGradientColor._alphaElements);
  17384. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, minGradientColor._rgbElements);
  17385. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS, maxGradientColor._alphaElements);
  17386. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS, maxGradientColor._rgbElements);
  17387. break;
  17388. }
  17389. }
  17390. else {
  17391. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  17392. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  17393. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, gradientColor._alphaElements);
  17394. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, gradientColor._rgbElements);
  17395. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, minGradientColor._alphaElements);
  17396. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, minGradientColor._rgbElements);
  17397. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS, maxGradientColor._alphaElements);
  17398. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS, maxGradientColor._rgbElements);
  17399. }
  17400. this._colorOverLifetime = value;
  17401. }
  17402. get sizeOverLifetime() {
  17403. return this._sizeOverLifetime;
  17404. }
  17405. set sizeOverLifetime(value) {
  17406. var shaDat = this._owner._render._shaderValues;
  17407. if (value) {
  17408. var size = value.size;
  17409. var sizeSeparate = size.separateAxes;
  17410. var sizeType = size.type;
  17411. if (value.enbale) {
  17412. switch (sizeType) {
  17413. case 0:
  17414. if (sizeSeparate)
  17415. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  17416. else
  17417. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  17418. break;
  17419. case 2:
  17420. if (sizeSeparate)
  17421. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  17422. else
  17423. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  17424. break;
  17425. }
  17426. }
  17427. else {
  17428. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  17429. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  17430. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  17431. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  17432. }
  17433. switch (sizeType) {
  17434. case 0:
  17435. if (sizeSeparate) {
  17436. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX, size.gradientX._elements);
  17437. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY, size.gradientY._elements);
  17438. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ, size.gradientZ._elements);
  17439. }
  17440. else {
  17441. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT, size.gradient._elements);
  17442. }
  17443. break;
  17444. case 2:
  17445. if (sizeSeparate) {
  17446. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX, size.gradientXMin._elements);
  17447. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTXMAX, size.gradientXMax._elements);
  17448. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY, size.gradientYMin._elements);
  17449. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTYMAX, size.gradientYMax._elements);
  17450. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ, size.gradientZMin._elements);
  17451. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZMAX, size.gradientZMax._elements);
  17452. }
  17453. else {
  17454. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT, size.gradientMin._elements);
  17455. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientMax, size.gradientMax._elements);
  17456. }
  17457. break;
  17458. }
  17459. }
  17460. else {
  17461. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  17462. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  17463. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  17464. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  17465. }
  17466. this._sizeOverLifetime = value;
  17467. }
  17468. get rotationOverLifetime() {
  17469. return this._rotationOverLifetime;
  17470. }
  17471. set rotationOverLifetime(value) {
  17472. var shaDat = this._owner._render._shaderValues;
  17473. if (value) {
  17474. var rotation = value.angularVelocity;
  17475. if (!rotation)
  17476. return;
  17477. var rotationSeparate = rotation.separateAxes;
  17478. var rotationType = rotation.type;
  17479. if (value.enbale) {
  17480. if (rotationSeparate)
  17481. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  17482. else
  17483. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  17484. switch (rotationType) {
  17485. case 0:
  17486. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  17487. break;
  17488. case 1:
  17489. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  17490. break;
  17491. case 2:
  17492. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  17493. break;
  17494. case 3:
  17495. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  17496. break;
  17497. }
  17498. }
  17499. else {
  17500. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  17501. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  17502. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  17503. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  17504. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  17505. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  17506. }
  17507. switch (rotationType) {
  17508. case 0:
  17509. if (rotationSeparate) {
  17510. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE, rotation.constantSeparate);
  17511. }
  17512. else {
  17513. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST, rotation.constant);
  17514. }
  17515. break;
  17516. case 1:
  17517. if (rotationSeparate) {
  17518. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX, rotation.gradientX._elements);
  17519. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY, rotation.gradientY._elements);
  17520. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ, rotation.gradientZ._elements);
  17521. }
  17522. else {
  17523. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT, rotation.gradient._elements);
  17524. }
  17525. break;
  17526. case 2:
  17527. if (rotationSeparate) {
  17528. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE, rotation.constantMinSeparate);
  17529. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAXSEPRARATE, rotation.constantMaxSeparate);
  17530. }
  17531. else {
  17532. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST, rotation.constantMin);
  17533. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAX, rotation.constantMax);
  17534. }
  17535. break;
  17536. case 3:
  17537. if (rotationSeparate) {
  17538. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX, rotation.gradientXMin._elements);
  17539. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTXMAX, rotation.gradientXMax._elements);
  17540. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY, rotation.gradientYMin._elements);
  17541. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTYMAX, rotation.gradientYMax._elements);
  17542. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ, rotation.gradientZMin._elements);
  17543. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZMAX, rotation.gradientZMax._elements);
  17544. }
  17545. else {
  17546. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT, rotation.gradientMin._elements);
  17547. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTMAX, rotation.gradientMax._elements);
  17548. }
  17549. break;
  17550. }
  17551. }
  17552. else {
  17553. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  17554. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  17555. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  17556. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  17557. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  17558. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  17559. }
  17560. this._rotationOverLifetime = value;
  17561. }
  17562. get textureSheetAnimation() {
  17563. return this._textureSheetAnimation;
  17564. }
  17565. set textureSheetAnimation(value) {
  17566. var shaDat = this._owner._render._shaderValues;
  17567. if (value) {
  17568. var frameOverTime = value.frame;
  17569. var textureAniType = frameOverTime.type;
  17570. if (value.enable) {
  17571. switch (textureAniType) {
  17572. case 1:
  17573. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  17574. break;
  17575. case 3:
  17576. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  17577. break;
  17578. }
  17579. }
  17580. else {
  17581. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  17582. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  17583. }
  17584. if (textureAniType === 1 || textureAniType === 3) {
  17585. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONCYCLES, value.cycles);
  17586. var title = value.tiles;
  17587. var _uvLengthE = this._uvLength;
  17588. _uvLengthE.x = 1.0 / title.x;
  17589. _uvLengthE.y = 1.0 / title.y;
  17590. shaDat.setVector2(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONSUBUVLENGTH, this._uvLength);
  17591. }
  17592. switch (textureAniType) {
  17593. case 1:
  17594. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS, frameOverTime.frameOverTimeData._elements);
  17595. break;
  17596. case 3:
  17597. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS, frameOverTime.frameOverTimeDataMin._elements);
  17598. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTMAXUVS, frameOverTime.frameOverTimeDataMax._elements);
  17599. break;
  17600. }
  17601. }
  17602. else {
  17603. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  17604. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  17605. }
  17606. this._textureSheetAnimation = value;
  17607. }
  17608. _getVertexBuffer(index = 0) {
  17609. if (index === 0)
  17610. return this._vertexBuffer;
  17611. else
  17612. return null;
  17613. }
  17614. _getIndexBuffer() {
  17615. return this._indexBuffer;
  17616. }
  17617. _generateBoundingSphere() {
  17618. var centerE = this._boundingSphere.center;
  17619. centerE.x = 0;
  17620. centerE.y = 0;
  17621. centerE.z = 0;
  17622. this._boundingSphere.radius = Number.MAX_VALUE;
  17623. }
  17624. _generateBoundingBox() {
  17625. var particle = this._owner;
  17626. var particleRender = particle.particleRenderer;
  17627. var boundMin = this._boundingBox.min;
  17628. var boundMax = this._boundingBox.max;
  17629. var i, n;
  17630. var maxStartLifeTime;
  17631. switch (this.startLifetimeType) {
  17632. case 0:
  17633. maxStartLifeTime = this.startLifetimeConstant;
  17634. break;
  17635. case 1:
  17636. maxStartLifeTime = -Number.MAX_VALUE;
  17637. var startLifeTimeGradient = startLifeTimeGradient;
  17638. for (i = 0, n = startLifeTimeGradient.gradientCount; i < n; i++)
  17639. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradient.getValueByIndex(i));
  17640. break;
  17641. case 2:
  17642. maxStartLifeTime = Math.max(this.startLifetimeConstantMin, this.startLifetimeConstantMax);
  17643. break;
  17644. case 3:
  17645. maxStartLifeTime = -Number.MAX_VALUE;
  17646. var startLifeTimeGradientMin = startLifeTimeGradientMin;
  17647. for (i = 0, n = startLifeTimeGradientMin.gradientCount; i < n; i++)
  17648. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradientMin.getValueByIndex(i));
  17649. var startLifeTimeGradientMax = startLifeTimeGradientMax;
  17650. for (i = 0, n = startLifeTimeGradientMax.gradientCount; i < n; i++)
  17651. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradientMax.getValueByIndex(i));
  17652. break;
  17653. }
  17654. var minStartSpeed, maxStartSpeed;
  17655. switch (this.startSpeedType) {
  17656. case 0:
  17657. minStartSpeed = maxStartSpeed = this.startSpeedConstant;
  17658. break;
  17659. case 1:
  17660. break;
  17661. case 2:
  17662. minStartSpeed = this.startLifetimeConstantMin;
  17663. maxStartSpeed = this.startLifetimeConstantMax;
  17664. break;
  17665. case 3:
  17666. break;
  17667. }
  17668. var minPosition, maxPosition, minDirection, maxDirection;
  17669. if (this._shape && this._shape.enable) ;
  17670. else {
  17671. minPosition = maxPosition = Vector3._ZERO;
  17672. minDirection = Vector3._ZERO;
  17673. maxDirection = Vector3._UnitZ;
  17674. }
  17675. var startMinVelocity = new Vector3(minDirection.x * minStartSpeed, minDirection.y * minStartSpeed, minDirection.z * minStartSpeed);
  17676. var startMaxVelocity = new Vector3(maxDirection.x * maxStartSpeed, maxDirection.y * maxStartSpeed, maxDirection.z * maxStartSpeed);
  17677. if (this._velocityOverLifetime && this._velocityOverLifetime.enbale) {
  17678. var lifeMinVelocity;
  17679. var lifeMaxVelocity;
  17680. var velocity = this._velocityOverLifetime.velocity;
  17681. switch (velocity.type) {
  17682. case 0:
  17683. lifeMinVelocity = lifeMaxVelocity = velocity.constant;
  17684. break;
  17685. case 1:
  17686. lifeMinVelocity = lifeMaxVelocity = new Vector3(velocity.gradientX.getAverageValue(), velocity.gradientY.getAverageValue(), velocity.gradientZ.getAverageValue());
  17687. break;
  17688. case 2:
  17689. lifeMinVelocity = velocity.constantMin;
  17690. lifeMaxVelocity = velocity.constantMax;
  17691. break;
  17692. case 3:
  17693. lifeMinVelocity = new Vector3(velocity.gradientXMin.getAverageValue(), velocity.gradientYMin.getAverageValue(), velocity.gradientZMin.getAverageValue());
  17694. lifeMaxVelocity = new Vector3(velocity.gradientXMax.getAverageValue(), velocity.gradientYMax.getAverageValue(), velocity.gradientZMax.getAverageValue());
  17695. break;
  17696. }
  17697. }
  17698. var positionScale, velocityScale;
  17699. var transform = this._owner.transform;
  17700. var worldPosition = transform.position;
  17701. var sizeScale = ShurikenParticleSystem._tempVector39;
  17702. var renderMode = particleRender.renderMode;
  17703. switch (this.scaleMode) {
  17704. case 0:
  17705. var scale = transform.getWorldLossyScale();
  17706. positionScale = scale;
  17707. sizeScale.x = scale.x;
  17708. sizeScale.y = scale.z;
  17709. sizeScale.z = scale.y;
  17710. (renderMode === 1) && (velocityScale = scale);
  17711. break;
  17712. case 1:
  17713. var localScale = transform.localScale;
  17714. positionScale = localScale;
  17715. sizeScale.x = localScale.x;
  17716. sizeScale.y = localScale.z;
  17717. sizeScale.z = localScale.y;
  17718. (renderMode === 1) && (velocityScale = localScale);
  17719. break;
  17720. case 2:
  17721. positionScale = transform.getWorldLossyScale();
  17722. sizeScale.x = sizeScale.y = sizeScale.z = 1;
  17723. (renderMode === 1) && (velocityScale = Vector3._ONE);
  17724. break;
  17725. }
  17726. var minStratPosition, maxStratPosition;
  17727. if (this._velocityOverLifetime && this._velocityOverLifetime.enbale) ;
  17728. else {
  17729. minStratPosition = new Vector3(startMinVelocity.x * maxStartLifeTime, startMinVelocity.y * maxStartLifeTime, startMinVelocity.z * maxStartLifeTime);
  17730. maxStratPosition = new Vector3(startMaxVelocity.x * maxStartLifeTime, startMaxVelocity.y * maxStartLifeTime, startMaxVelocity.z * maxStartLifeTime);
  17731. if (this.scaleMode != 2) {
  17732. Vector3.add(minPosition, minStratPosition, boundMin);
  17733. Vector3.multiply(positionScale, boundMin, boundMin);
  17734. Vector3.add(maxPosition, maxStratPosition, boundMax);
  17735. Vector3.multiply(positionScale, boundMax, boundMax);
  17736. }
  17737. else {
  17738. Vector3.multiply(positionScale, minPosition, boundMin);
  17739. Vector3.add(boundMin, minStratPosition, boundMin);
  17740. Vector3.multiply(positionScale, maxPosition, boundMax);
  17741. Vector3.add(boundMax, maxStratPosition, boundMax);
  17742. }
  17743. }
  17744. switch (this.simulationSpace) {
  17745. case 0:
  17746. break;
  17747. case 1:
  17748. Vector3.add(boundMin, worldPosition, boundMin);
  17749. Vector3.add(boundMax, worldPosition, boundMax);
  17750. break;
  17751. }
  17752. var maxSize, maxSizeY;
  17753. switch (this.startSizeType) {
  17754. case 0:
  17755. if (this.threeDStartSize) {
  17756. var startSizeConstantSeparate = startSizeConstantSeparate;
  17757. maxSize = Math.max(startSizeConstantSeparate.x, startSizeConstantSeparate.y);
  17758. if (renderMode === 1)
  17759. maxSizeY = startSizeConstantSeparate.y;
  17760. }
  17761. else {
  17762. maxSize = this.startSizeConstant;
  17763. if (renderMode === 1)
  17764. maxSizeY = this.startSizeConstant;
  17765. }
  17766. break;
  17767. case 1:
  17768. break;
  17769. case 2:
  17770. if (this.threeDStartSize) {
  17771. var startSizeConstantMaxSeparate = startSizeConstantMaxSeparate;
  17772. maxSize = Math.max(startSizeConstantMaxSeparate.x, startSizeConstantMaxSeparate.y);
  17773. if (renderMode === 1)
  17774. maxSizeY = startSizeConstantMaxSeparate.y;
  17775. }
  17776. else {
  17777. maxSize = this.startSizeConstantMax;
  17778. if (renderMode === 1)
  17779. maxSizeY = this.startSizeConstantMax;
  17780. }
  17781. break;
  17782. case 3:
  17783. break;
  17784. }
  17785. if (this._sizeOverLifetime && this._sizeOverLifetime.enbale) {
  17786. var size = this._sizeOverLifetime.size;
  17787. maxSize *= this._sizeOverLifetime.size.getMaxSizeInGradient();
  17788. }
  17789. var threeDMaxSize = ShurikenParticleSystem._tempVector30;
  17790. var rotSize, nonRotSize;
  17791. switch (renderMode) {
  17792. case 0:
  17793. rotSize = maxSize * ShurikenParticleSystem.halfKSqrtOf2;
  17794. Vector3.scale(sizeScale, maxSize, threeDMaxSize);
  17795. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  17796. Vector3.add(boundMax, threeDMaxSize, boundMax);
  17797. break;
  17798. case 1:
  17799. var maxStretchPosition = ShurikenParticleSystem._tempVector31;
  17800. var maxStretchVelocity = ShurikenParticleSystem._tempVector32;
  17801. var minStretchVelocity = ShurikenParticleSystem._tempVector33;
  17802. var minStretchPosition = ShurikenParticleSystem._tempVector34;
  17803. if (this._velocityOverLifetime && this._velocityOverLifetime.enbale) ;
  17804. else {
  17805. Vector3.multiply(velocityScale, startMaxVelocity, maxStretchVelocity);
  17806. Vector3.multiply(velocityScale, startMinVelocity, minStretchVelocity);
  17807. }
  17808. var sizeStretch = maxSizeY * particleRender.stretchedBillboardLengthScale;
  17809. var maxStretchLength = Vector3.scalarLength(maxStretchVelocity) * particleRender.stretchedBillboardSpeedScale + sizeStretch;
  17810. var minStretchLength = Vector3.scalarLength(minStretchVelocity) * particleRender.stretchedBillboardSpeedScale + sizeStretch;
  17811. var norMaxStretchVelocity = ShurikenParticleSystem._tempVector35;
  17812. var norMinStretchVelocity = ShurikenParticleSystem._tempVector36;
  17813. Vector3.normalize(maxStretchVelocity, norMaxStretchVelocity);
  17814. Vector3.scale(norMaxStretchVelocity, maxStretchLength, minStretchPosition);
  17815. Vector3.subtract(maxStratPosition, minStretchPosition, minStretchPosition);
  17816. Vector3.normalize(minStretchVelocity, norMinStretchVelocity);
  17817. Vector3.scale(norMinStretchVelocity, minStretchLength, maxStretchPosition);
  17818. Vector3.add(minStratPosition, maxStretchPosition, maxStretchPosition);
  17819. rotSize = maxSize * ShurikenParticleSystem.halfKSqrtOf2;
  17820. Vector3.scale(sizeScale, rotSize, threeDMaxSize);
  17821. var halfNorMaxStretchVelocity = ShurikenParticleSystem._tempVector37;
  17822. var halfNorMinStretchVelocity = ShurikenParticleSystem._tempVector38;
  17823. Vector3.scale(norMaxStretchVelocity, 0.5, halfNorMaxStretchVelocity);
  17824. Vector3.scale(norMinStretchVelocity, 0.5, halfNorMinStretchVelocity);
  17825. Vector3.multiply(halfNorMaxStretchVelocity, sizeScale, halfNorMaxStretchVelocity);
  17826. Vector3.multiply(halfNorMinStretchVelocity, sizeScale, halfNorMinStretchVelocity);
  17827. Vector3.add(boundMin, halfNorMinStretchVelocity, boundMin);
  17828. Vector3.min(boundMin, minStretchPosition, boundMin);
  17829. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  17830. Vector3.subtract(boundMax, halfNorMaxStretchVelocity, boundMax);
  17831. Vector3.max(boundMax, maxStretchPosition, boundMax);
  17832. Vector3.add(boundMax, threeDMaxSize, boundMax);
  17833. break;
  17834. case 2:
  17835. maxSize *= Math.cos(0.78539816339744830961566084581988);
  17836. nonRotSize = maxSize * 0.5;
  17837. threeDMaxSize.x = sizeScale.x * nonRotSize;
  17838. threeDMaxSize.y = sizeScale.z * nonRotSize;
  17839. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  17840. Vector3.add(boundMax, threeDMaxSize, boundMax);
  17841. break;
  17842. case 3:
  17843. maxSize *= Math.cos(0.78539816339744830961566084581988);
  17844. nonRotSize = maxSize * 0.5;
  17845. Vector3.scale(sizeScale, nonRotSize, threeDMaxSize);
  17846. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  17847. Vector3.add(boundMax, threeDMaxSize, boundMax);
  17848. break;
  17849. }
  17850. this._boundingBox.getCorners(this._boundingBoxCorners);
  17851. }
  17852. _updateEmission() {
  17853. if (!this.isAlive)
  17854. return;
  17855. if (this._simulateUpdate) {
  17856. this._simulateUpdate = false;
  17857. }
  17858. else {
  17859. var elapsedTime = (this._startUpdateLoopCount !== Laya.Stat.loopCount && !this._isPaused) ? this._owner._scene.timer._delta / 1000.0 : 0;
  17860. elapsedTime = Math.min(ShurikenParticleSystem._maxElapsedTime, elapsedTime * this.simulationSpeed);
  17861. this._updateParticles(elapsedTime);
  17862. }
  17863. }
  17864. _updateParticles(elapsedTime) {
  17865. if (this._ownerRender.renderMode === 4 && !this._ownerRender.mesh)
  17866. return;
  17867. this._currentTime += elapsedTime;
  17868. this._retireActiveParticles();
  17869. this._freeRetiredParticles();
  17870. this._totalDelayTime += elapsedTime;
  17871. if (this._totalDelayTime < this._playStartDelay) {
  17872. return;
  17873. }
  17874. if (this._emission.enbale && this._isEmitting && !this._isPaused)
  17875. this._advanceTime(elapsedTime, this._currentTime);
  17876. }
  17877. _updateParticlesSimulationRestart(time) {
  17878. this._firstActiveElement = 0;
  17879. this._firstNewElement = 0;
  17880. this._firstFreeElement = 0;
  17881. this._firstRetiredElement = 0;
  17882. this._burstsIndex = 0;
  17883. this._frameRateTime = time;
  17884. this._emissionTime = 0;
  17885. this._totalDelayTime = 0;
  17886. this._currentTime = time;
  17887. var delayTime = time;
  17888. if (delayTime < this._playStartDelay) {
  17889. this._totalDelayTime = delayTime;
  17890. return;
  17891. }
  17892. if (this._emission.enbale)
  17893. this._advanceTime(time, time);
  17894. }
  17895. _retireActiveParticles() {
  17896. const epsilon = 0.0001;
  17897. while (this._firstActiveElement != this._firstNewElement) {
  17898. var index = this._firstActiveElement * this._floatCountPerVertex * this._vertexStride;
  17899. var timeIndex = index + this._timeIndex;
  17900. var particleAge = this._currentTime - this._vertices[timeIndex];
  17901. if (particleAge + epsilon < this._vertices[index + this._startLifeTimeIndex])
  17902. break;
  17903. this._vertices[timeIndex] = this._drawCounter;
  17904. this._firstActiveElement++;
  17905. if (this._firstActiveElement >= this._bufferMaxParticles)
  17906. this._firstActiveElement = 0;
  17907. }
  17908. }
  17909. _freeRetiredParticles() {
  17910. while (this._firstRetiredElement != this._firstActiveElement) {
  17911. var age = this._drawCounter - this._vertices[this._firstRetiredElement * this._floatCountPerVertex * this._vertexStride + this._timeIndex];
  17912. if (this.isPerformanceMode)
  17913. if (age < 3)
  17914. break;
  17915. this._firstRetiredElement++;
  17916. if (this._firstRetiredElement >= this._bufferMaxParticles)
  17917. this._firstRetiredElement = 0;
  17918. }
  17919. }
  17920. _burst(fromTime, toTime) {
  17921. var totalEmitCount = 0;
  17922. var bursts = this._emission._bursts;
  17923. for (var n = bursts.length; this._burstsIndex < n; this._burstsIndex++) {
  17924. var burst = bursts[this._burstsIndex];
  17925. var burstTime = burst.time;
  17926. if (fromTime <= burstTime && burstTime < toTime) {
  17927. var emitCount;
  17928. if (this.autoRandomSeed) {
  17929. emitCount = Laya.MathUtil.lerp(burst.minCount, burst.maxCount, Math.random());
  17930. }
  17931. else {
  17932. this._rand.seed = this._randomSeeds[0];
  17933. emitCount = Laya.MathUtil.lerp(burst.minCount, burst.maxCount, this._rand.getFloat());
  17934. this._randomSeeds[0] = this._rand.seed;
  17935. }
  17936. totalEmitCount += emitCount;
  17937. }
  17938. else {
  17939. break;
  17940. }
  17941. }
  17942. return totalEmitCount;
  17943. }
  17944. _advanceTime(elapsedTime, emitTime) {
  17945. var i;
  17946. var lastEmissionTime = this._emissionTime;
  17947. this._emissionTime += elapsedTime;
  17948. var totalEmitCount = 0;
  17949. if (this._emissionTime > this.duration) {
  17950. if (this.looping) {
  17951. totalEmitCount += this._burst(lastEmissionTime, this._emissionTime);
  17952. this._emissionTime -= this.duration;
  17953. this._burstsIndex = 0;
  17954. totalEmitCount += this._burst(0, this._emissionTime);
  17955. }
  17956. else {
  17957. totalEmitCount = Math.min(this.maxParticles - this.aliveParticleCount, totalEmitCount);
  17958. for (i = 0; i < totalEmitCount; i++)
  17959. this.emit(emitTime);
  17960. this._isPlaying = false;
  17961. this.stop();
  17962. return;
  17963. }
  17964. }
  17965. else {
  17966. totalEmitCount += this._burst(lastEmissionTime, this._emissionTime);
  17967. }
  17968. totalEmitCount = Math.min(this.maxParticles - this.aliveParticleCount, totalEmitCount);
  17969. for (i = 0; i < totalEmitCount; i++)
  17970. this.emit(emitTime);
  17971. var emissionRate = this.emission.emissionRate;
  17972. if (emissionRate > 0) {
  17973. var minEmissionTime = 1 / emissionRate;
  17974. this._frameRateTime += minEmissionTime;
  17975. this._frameRateTime = this._currentTime - (this._currentTime - this._frameRateTime) % this._maxStartLifetime;
  17976. while (this._frameRateTime <= emitTime) {
  17977. if (this.emit(this._frameRateTime))
  17978. this._frameRateTime += minEmissionTime;
  17979. else
  17980. break;
  17981. }
  17982. this._frameRateTime = Math.floor(emitTime / minEmissionTime) * minEmissionTime;
  17983. }
  17984. }
  17985. _initBufferDatas() {
  17986. if (this._vertexBuffer) {
  17987. this._vertexBuffer.destroy();
  17988. this._indexBuffer.destroy();
  17989. }
  17990. var gl = Laya.LayaGL.instance;
  17991. var render = this._ownerRender;
  17992. var renderMode = render.renderMode;
  17993. if (renderMode !== -1 && this.maxParticles > 0) {
  17994. var indices, i, j, m, indexOffset, perPartOffset, vertexDeclaration;
  17995. var vbMemorySize = 0, memorySize = 0;
  17996. var mesh = render.mesh;
  17997. if (renderMode === 4) {
  17998. if (mesh) {
  17999. vertexDeclaration = VertexShurikenParticleMesh.vertexDeclaration;
  18000. this._floatCountPerVertex = vertexDeclaration.vertexStride / 4;
  18001. this._startLifeTimeIndex = 12;
  18002. this._timeIndex = 16;
  18003. this._vertexStride = mesh._vertexCount;
  18004. var totalVertexCount = this._bufferMaxParticles * this._vertexStride;
  18005. var vbCount = Math.floor(totalVertexCount / 65535) + 1;
  18006. var lastVBVertexCount = totalVertexCount % 65535;
  18007. if (vbCount > 1) {
  18008. throw new Error("ShurikenParticleSystem:the maxParticleCount multiply mesh vertexCount is large than 65535.");
  18009. }
  18010. vbMemorySize = vertexDeclaration.vertexStride * lastVBVertexCount;
  18011. this._vertexBuffer = new VertexBuffer3D(vbMemorySize, gl.DYNAMIC_DRAW);
  18012. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  18013. this._vertices = new Float32Array(this._floatCountPerVertex * lastVBVertexCount);
  18014. this._indexStride = mesh._indexBuffer.indexCount;
  18015. var indexDatas = mesh._indexBuffer.getData();
  18016. var indexCount = this._bufferMaxParticles * this._indexStride;
  18017. this._indexBuffer = new IndexBuffer3D(IndexBuffer3D.INDEXTYPE_USHORT, indexCount, gl.STATIC_DRAW);
  18018. indices = new Uint16Array(indexCount);
  18019. memorySize = vbMemorySize + indexCount * 2;
  18020. indexOffset = 0;
  18021. for (i = 0; i < this._bufferMaxParticles; i++) {
  18022. var indexValueOffset = i * this._vertexStride;
  18023. for (j = 0, m = indexDatas.length; j < m; j++)
  18024. indices[indexOffset++] = indexValueOffset + indexDatas[j];
  18025. }
  18026. this._indexBuffer.setData(indices);
  18027. this._bufferState.bind();
  18028. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  18029. this._bufferState.applyIndexBuffer(this._indexBuffer);
  18030. this._bufferState.unBind();
  18031. }
  18032. }
  18033. else {
  18034. vertexDeclaration = VertexShurikenParticleBillboard.vertexDeclaration;
  18035. this._floatCountPerVertex = vertexDeclaration.vertexStride / 4;
  18036. this._startLifeTimeIndex = 7;
  18037. this._timeIndex = 11;
  18038. this._vertexStride = 4;
  18039. vbMemorySize = vertexDeclaration.vertexStride * this._bufferMaxParticles * this._vertexStride;
  18040. this._vertexBuffer = new VertexBuffer3D(vbMemorySize, gl.DYNAMIC_DRAW);
  18041. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  18042. this._vertices = new Float32Array(this._floatCountPerVertex * this._bufferMaxParticles * this._vertexStride);
  18043. for (i = 0; i < this._bufferMaxParticles; i++) {
  18044. perPartOffset = i * this._floatCountPerVertex * this._vertexStride;
  18045. this._vertices[perPartOffset] = -0.5;
  18046. this._vertices[perPartOffset + 1] = -0.5;
  18047. this._vertices[perPartOffset + 2] = 0;
  18048. this._vertices[perPartOffset + 3] = 1;
  18049. perPartOffset += this._floatCountPerVertex;
  18050. this._vertices[perPartOffset] = 0.5;
  18051. this._vertices[perPartOffset + 1] = -0.5;
  18052. this._vertices[perPartOffset + 2] = 1;
  18053. this._vertices[perPartOffset + 3] = 1;
  18054. perPartOffset += this._floatCountPerVertex;
  18055. this._vertices[perPartOffset] = 0.5;
  18056. this._vertices[perPartOffset + 1] = 0.5;
  18057. this._vertices[perPartOffset + 2] = 1;
  18058. this._vertices[perPartOffset + 3] = 0;
  18059. perPartOffset += this._floatCountPerVertex;
  18060. this._vertices[perPartOffset] = -0.5;
  18061. this._vertices[perPartOffset + 1] = 0.5;
  18062. this._vertices[perPartOffset + 2] = 0;
  18063. this._vertices[perPartOffset + 3] = 0;
  18064. }
  18065. this._indexStride = 6;
  18066. this._indexBuffer = new IndexBuffer3D(IndexBuffer3D.INDEXTYPE_USHORT, this._bufferMaxParticles * 6, gl.STATIC_DRAW);
  18067. indices = new Uint16Array(this._bufferMaxParticles * 6);
  18068. for (i = 0; i < this._bufferMaxParticles; i++) {
  18069. indexOffset = i * 6;
  18070. var firstVertex = i * this._vertexStride, secondVertex = firstVertex + 2;
  18071. indices[indexOffset++] = firstVertex;
  18072. indices[indexOffset++] = secondVertex;
  18073. indices[indexOffset++] = firstVertex + 1;
  18074. indices[indexOffset++] = firstVertex;
  18075. indices[indexOffset++] = firstVertex + 3;
  18076. indices[indexOffset++] = secondVertex;
  18077. }
  18078. this._indexBuffer.setData(indices);
  18079. memorySize = vbMemorySize + this._bufferMaxParticles * 6 * 2;
  18080. this._bufferState.bind();
  18081. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  18082. this._bufferState.applyIndexBuffer(this._indexBuffer);
  18083. this._bufferState.unBind();
  18084. }
  18085. Laya.Resource._addMemory(memorySize, memorySize);
  18086. }
  18087. }
  18088. destroy() {
  18089. super.destroy();
  18090. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer.indexCount * 2;
  18091. Laya.Resource._addMemory(-memorySize, -memorySize);
  18092. this._bufferState.destroy();
  18093. this._vertexBuffer.destroy();
  18094. this._indexBuffer.destroy();
  18095. this._emission.destroy();
  18096. this._bufferState = null;
  18097. this._vertexBuffer = null;
  18098. this._indexBuffer = null;
  18099. this._owner = null;
  18100. this._vertices = null;
  18101. this._indexBuffer = null;
  18102. this._emission = null;
  18103. this._shape = null;
  18104. this.startLifeTimeGradient = null;
  18105. this.startLifeTimeGradientMin = null;
  18106. this.startLifeTimeGradientMax = null;
  18107. this.startSizeConstantSeparate = null;
  18108. this.startSizeConstantMinSeparate = null;
  18109. this.startSizeConstantMaxSeparate = null;
  18110. this.startRotationConstantSeparate = null;
  18111. this.startRotationConstantMinSeparate = null;
  18112. this.startRotationConstantMaxSeparate = null;
  18113. this.startColorConstant = null;
  18114. this.startColorConstantMin = null;
  18115. this.startColorConstantMax = null;
  18116. this._velocityOverLifetime = null;
  18117. this._colorOverLifetime = null;
  18118. this._sizeOverLifetime = null;
  18119. this._rotationOverLifetime = null;
  18120. this._textureSheetAnimation = null;
  18121. }
  18122. emit(time) {
  18123. var position = ShurikenParticleSystem._tempPosition;
  18124. var direction = ShurikenParticleSystem._tempDirection;
  18125. if (this._shape && this._shape.enable) {
  18126. if (this.autoRandomSeed)
  18127. this._shape.generatePositionAndDirection(position, direction);
  18128. else
  18129. this._shape.generatePositionAndDirection(position, direction, this._rand, this._randomSeeds);
  18130. }
  18131. else {
  18132. position.x = position.y = position.z = 0;
  18133. direction.x = direction.y = 0;
  18134. direction.z = 1;
  18135. }
  18136. return this.addParticle(position, direction, time);
  18137. }
  18138. addParticle(position, direction, time) {
  18139. Vector3.normalize(direction, direction);
  18140. var nextFreeParticle = this._firstFreeElement + 1;
  18141. if (nextFreeParticle >= this._bufferMaxParticles)
  18142. nextFreeParticle = 0;
  18143. if (nextFreeParticle === this._firstRetiredElement)
  18144. return false;
  18145. var transform = this._owner.transform;
  18146. ShurikenParticleData.create(this, this._ownerRender, transform);
  18147. var particleAge = this._currentTime - time;
  18148. if (particleAge >= ShurikenParticleData.startLifeTime)
  18149. return true;
  18150. var pos, rot;
  18151. if (this.simulationSpace == 0) {
  18152. pos = transform.position;
  18153. rot = transform.rotation;
  18154. }
  18155. var startSpeed;
  18156. switch (this.startSpeedType) {
  18157. case 0:
  18158. startSpeed = this.startSpeedConstant;
  18159. break;
  18160. case 2:
  18161. if (this.autoRandomSeed) {
  18162. startSpeed = Laya.MathUtil.lerp(this.startSpeedConstantMin, this.startSpeedConstantMax, Math.random());
  18163. }
  18164. else {
  18165. this._rand.seed = this._randomSeeds[8];
  18166. startSpeed = Laya.MathUtil.lerp(this.startSpeedConstantMin, this.startSpeedConstantMax, this._rand.getFloat());
  18167. this._randomSeeds[8] = this._rand.seed;
  18168. }
  18169. break;
  18170. }
  18171. var randomVelocityX, randomVelocityY, randomVelocityZ, randomColor, randomSize, randomRotation, randomTextureAnimation;
  18172. var needRandomVelocity = this._velocityOverLifetime && this._velocityOverLifetime.enbale;
  18173. if (needRandomVelocity) {
  18174. var velocityType = this._velocityOverLifetime.velocity.type;
  18175. if (velocityType === 2 || velocityType === 3) {
  18176. if (this.autoRandomSeed) {
  18177. randomVelocityX = Math.random();
  18178. randomVelocityY = Math.random();
  18179. randomVelocityZ = Math.random();
  18180. }
  18181. else {
  18182. this._rand.seed = this._randomSeeds[9];
  18183. randomVelocityX = this._rand.getFloat();
  18184. randomVelocityY = this._rand.getFloat();
  18185. randomVelocityZ = this._rand.getFloat();
  18186. this._randomSeeds[9] = this._rand.seed;
  18187. }
  18188. }
  18189. else {
  18190. needRandomVelocity = false;
  18191. }
  18192. }
  18193. else {
  18194. needRandomVelocity = false;
  18195. }
  18196. var needRandomColor = this._colorOverLifetime && this._colorOverLifetime.enbale;
  18197. if (needRandomColor) {
  18198. var colorType = this._colorOverLifetime.color.type;
  18199. if (colorType === 3) {
  18200. if (this.autoRandomSeed) {
  18201. randomColor = Math.random();
  18202. }
  18203. else {
  18204. this._rand.seed = this._randomSeeds[10];
  18205. randomColor = this._rand.getFloat();
  18206. this._randomSeeds[10] = this._rand.seed;
  18207. }
  18208. }
  18209. else {
  18210. needRandomColor = false;
  18211. }
  18212. }
  18213. else {
  18214. needRandomColor = false;
  18215. }
  18216. var needRandomSize = this._sizeOverLifetime && this._sizeOverLifetime.enbale;
  18217. if (needRandomSize) {
  18218. var sizeType = this._sizeOverLifetime.size.type;
  18219. if (sizeType === 3) {
  18220. if (this.autoRandomSeed) {
  18221. randomSize = Math.random();
  18222. }
  18223. else {
  18224. this._rand.seed = this._randomSeeds[11];
  18225. randomSize = this._rand.getFloat();
  18226. this._randomSeeds[11] = this._rand.seed;
  18227. }
  18228. }
  18229. else {
  18230. needRandomSize = false;
  18231. }
  18232. }
  18233. else {
  18234. needRandomSize = false;
  18235. }
  18236. var needRandomRotation = this._rotationOverLifetime && this._rotationOverLifetime.enbale;
  18237. if (needRandomRotation) {
  18238. var rotationType = this._rotationOverLifetime.angularVelocity.type;
  18239. if (rotationType === 2 || rotationType === 3) {
  18240. if (this.autoRandomSeed) {
  18241. randomRotation = Math.random();
  18242. }
  18243. else {
  18244. this._rand.seed = this._randomSeeds[12];
  18245. randomRotation = this._rand.getFloat();
  18246. this._randomSeeds[12] = this._rand.seed;
  18247. }
  18248. }
  18249. else {
  18250. needRandomRotation = false;
  18251. }
  18252. }
  18253. else {
  18254. needRandomRotation = false;
  18255. }
  18256. var needRandomTextureAnimation = this._textureSheetAnimation && this._textureSheetAnimation.enable;
  18257. if (needRandomTextureAnimation) {
  18258. var textureAnimationType = this._textureSheetAnimation.frame.type;
  18259. if (textureAnimationType === 3) {
  18260. if (this.autoRandomSeed) {
  18261. randomTextureAnimation = Math.random();
  18262. }
  18263. else {
  18264. this._rand.seed = this._randomSeeds[15];
  18265. randomTextureAnimation = this._rand.getFloat();
  18266. this._randomSeeds[15] = this._rand.seed;
  18267. }
  18268. }
  18269. else {
  18270. needRandomTextureAnimation = false;
  18271. }
  18272. }
  18273. else {
  18274. needRandomTextureAnimation = false;
  18275. }
  18276. var startIndex = this._firstFreeElement * this._floatCountPerVertex * this._vertexStride;
  18277. var subU = ShurikenParticleData.startUVInfo[0];
  18278. var subV = ShurikenParticleData.startUVInfo[1];
  18279. var startU = ShurikenParticleData.startUVInfo[2];
  18280. var startV = ShurikenParticleData.startUVInfo[3];
  18281. var meshVertices, meshVertexStride, meshPosOffset, meshCorOffset, meshUVOffset, meshVertexIndex;
  18282. var render = this._ownerRender;
  18283. if (render.renderMode === 4) {
  18284. var meshVB = render.mesh._vertexBuffer;
  18285. meshVertices = meshVB.getFloat32Data();
  18286. var meshVertexDeclaration = meshVB.vertexDeclaration;
  18287. meshPosOffset = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  18288. var colorElement = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  18289. meshCorOffset = colorElement ? colorElement._offset / 4 : -1;
  18290. var uvElement = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  18291. meshUVOffset = uvElement ? uvElement._offset / 4 : -1;
  18292. meshVertexStride = meshVertexDeclaration.vertexStride / 4;
  18293. meshVertexIndex = 0;
  18294. }
  18295. else {
  18296. this._vertices[startIndex + 2] = startU;
  18297. this._vertices[startIndex + 3] = startV + subV;
  18298. var secondOffset = startIndex + this._floatCountPerVertex;
  18299. this._vertices[secondOffset + 2] = startU + subU;
  18300. this._vertices[secondOffset + 3] = startV + subV;
  18301. var thirdOffset = secondOffset + this._floatCountPerVertex;
  18302. this._vertices[thirdOffset + 2] = startU + subU;
  18303. this._vertices[thirdOffset + 3] = startV;
  18304. var fourthOffset = thirdOffset + this._floatCountPerVertex;
  18305. this._vertices[fourthOffset + 2] = startU;
  18306. this._vertices[fourthOffset + 3] = startV;
  18307. }
  18308. for (var i = startIndex, n = startIndex + this._floatCountPerVertex * this._vertexStride; i < n; i += this._floatCountPerVertex) {
  18309. var offset;
  18310. if (render.renderMode === 4) {
  18311. offset = i;
  18312. var vertexOffset = meshVertexStride * (meshVertexIndex++);
  18313. var meshOffset = vertexOffset + meshPosOffset;
  18314. this._vertices[offset++] = meshVertices[meshOffset++];
  18315. this._vertices[offset++] = meshVertices[meshOffset++];
  18316. this._vertices[offset++] = meshVertices[meshOffset];
  18317. if (meshCorOffset === -1) {
  18318. this._vertices[offset++] = 1.0;
  18319. this._vertices[offset++] = 1.0;
  18320. this._vertices[offset++] = 1.0;
  18321. this._vertices[offset++] = 1.0;
  18322. }
  18323. else {
  18324. meshOffset = vertexOffset + meshCorOffset;
  18325. this._vertices[offset++] = meshVertices[meshOffset++];
  18326. this._vertices[offset++] = meshVertices[meshOffset++];
  18327. this._vertices[offset++] = meshVertices[meshOffset++];
  18328. this._vertices[offset++] = meshVertices[meshOffset];
  18329. }
  18330. if (meshUVOffset === -1) {
  18331. this._vertices[offset++] = 0.0;
  18332. this._vertices[offset++] = 0.0;
  18333. }
  18334. else {
  18335. meshOffset = vertexOffset + meshUVOffset;
  18336. this._vertices[offset++] = startU + meshVertices[meshOffset++] * subU;
  18337. this._vertices[offset++] = startV + meshVertices[meshOffset] * subV;
  18338. }
  18339. }
  18340. else {
  18341. offset = i + 4;
  18342. }
  18343. this._vertices[offset++] = position.x;
  18344. this._vertices[offset++] = position.y;
  18345. this._vertices[offset++] = position.z;
  18346. this._vertices[offset++] = ShurikenParticleData.startLifeTime;
  18347. this._vertices[offset++] = direction.x;
  18348. this._vertices[offset++] = direction.y;
  18349. this._vertices[offset++] = direction.z;
  18350. this._vertices[offset++] = time;
  18351. this._vertices[offset++] = ShurikenParticleData.startColor.x;
  18352. this._vertices[offset++] = ShurikenParticleData.startColor.y;
  18353. this._vertices[offset++] = ShurikenParticleData.startColor.z;
  18354. this._vertices[offset++] = ShurikenParticleData.startColor.w;
  18355. this._vertices[offset++] = ShurikenParticleData.startSize[0];
  18356. this._vertices[offset++] = ShurikenParticleData.startSize[1];
  18357. this._vertices[offset++] = ShurikenParticleData.startSize[2];
  18358. this._vertices[offset++] = ShurikenParticleData.startRotation[0];
  18359. this._vertices[offset++] = ShurikenParticleData.startRotation[1];
  18360. this._vertices[offset++] = ShurikenParticleData.startRotation[2];
  18361. this._vertices[offset++] = startSpeed;
  18362. needRandomColor && (this._vertices[offset + 1] = randomColor);
  18363. needRandomSize && (this._vertices[offset + 2] = randomSize);
  18364. needRandomRotation && (this._vertices[offset + 3] = randomRotation);
  18365. needRandomTextureAnimation && (this._vertices[offset + 4] = randomTextureAnimation);
  18366. if (needRandomVelocity) {
  18367. this._vertices[offset + 5] = randomVelocityX;
  18368. this._vertices[offset + 6] = randomVelocityY;
  18369. this._vertices[offset + 7] = randomVelocityZ;
  18370. }
  18371. switch (this.simulationSpace) {
  18372. case 0:
  18373. offset += 8;
  18374. this._vertices[offset++] = pos.x;
  18375. this._vertices[offset++] = pos.y;
  18376. this._vertices[offset++] = pos.z;
  18377. this._vertices[offset++] = rot.x;
  18378. this._vertices[offset++] = rot.y;
  18379. this._vertices[offset++] = rot.z;
  18380. this._vertices[offset++] = rot.w;
  18381. break;
  18382. case 1:
  18383. break;
  18384. default:
  18385. throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid.");
  18386. }
  18387. }
  18388. this._firstFreeElement = nextFreeParticle;
  18389. return true;
  18390. }
  18391. addNewParticlesToVertexBuffer() {
  18392. var start;
  18393. var byteStride = this._vertexStride * this._floatCountPerVertex * 4;
  18394. if (this._firstNewElement < this._firstFreeElement) {
  18395. start = this._firstNewElement * byteStride;
  18396. this._vertexBuffer.setData(this._vertices.buffer, start, start, (this._firstFreeElement - this._firstNewElement) * byteStride);
  18397. }
  18398. else {
  18399. start = this._firstNewElement * byteStride;
  18400. this._vertexBuffer.setData(this._vertices.buffer, start, start, (this._bufferMaxParticles - this._firstNewElement) * byteStride);
  18401. if (this._firstFreeElement > 0) {
  18402. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, this._firstFreeElement * byteStride);
  18403. }
  18404. }
  18405. this._firstNewElement = this._firstFreeElement;
  18406. }
  18407. _getType() {
  18408. return ShurikenParticleSystem._type;
  18409. }
  18410. _prepareRender(state) {
  18411. this._updateEmission();
  18412. if (this._firstNewElement != this._firstFreeElement)
  18413. this.addNewParticlesToVertexBuffer();
  18414. this._drawCounter++;
  18415. if (this._firstActiveElement != this._firstFreeElement)
  18416. return true;
  18417. else
  18418. return false;
  18419. }
  18420. _render(state) {
  18421. this._bufferState.bind();
  18422. var indexCount;
  18423. var gl = Laya.LayaGL.instance;
  18424. if (this._firstActiveElement < this._firstFreeElement) {
  18425. indexCount = (this._firstFreeElement - this._firstActiveElement) * this._indexStride;
  18426. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 2 * this._firstActiveElement * this._indexStride);
  18427. Laya.Stat.trianglesFaces += indexCount / 3;
  18428. Laya.Stat.renderBatches++;
  18429. }
  18430. else {
  18431. indexCount = (this._bufferMaxParticles - this._firstActiveElement) * this._indexStride;
  18432. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 2 * this._firstActiveElement * this._indexStride);
  18433. Laya.Stat.trianglesFaces += indexCount / 3;
  18434. Laya.Stat.renderBatches++;
  18435. if (this._firstFreeElement > 0) {
  18436. indexCount = this._firstFreeElement * this._indexStride;
  18437. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  18438. Laya.Stat.trianglesFaces += indexCount / 3;
  18439. Laya.Stat.renderBatches++;
  18440. }
  18441. }
  18442. }
  18443. play() {
  18444. this._burstsIndex = 0;
  18445. this._isEmitting = true;
  18446. this._isPlaying = true;
  18447. this._isPaused = false;
  18448. this._emissionTime = 0;
  18449. this._totalDelayTime = 0;
  18450. if (!this.autoRandomSeed) {
  18451. for (var i = 0, n = this._randomSeeds.length; i < n; i++)
  18452. this._randomSeeds[i] = this.randomSeed[0] + ShurikenParticleSystem._RANDOMOFFSET[i];
  18453. }
  18454. switch (this.startDelayType) {
  18455. case 0:
  18456. this._playStartDelay = this.startDelay;
  18457. break;
  18458. case 1:
  18459. if (this.autoRandomSeed) {
  18460. this._playStartDelay = Laya.MathUtil.lerp(this.startDelayMin, this.startDelayMax, Math.random());
  18461. }
  18462. else {
  18463. this._rand.seed = this._randomSeeds[2];
  18464. this._playStartDelay = Laya.MathUtil.lerp(this.startDelayMin, this.startDelayMax, this._rand.getFloat());
  18465. this._randomSeeds[2] = this._rand.seed;
  18466. }
  18467. break;
  18468. default:
  18469. throw new Error("Utils3D: startDelayType is invalid.");
  18470. }
  18471. this._frameRateTime = this._currentTime + this._playStartDelay;
  18472. this._startUpdateLoopCount = Laya.Stat.loopCount;
  18473. }
  18474. pause() {
  18475. this._isPaused = true;
  18476. }
  18477. simulate(time, restart = true) {
  18478. this._simulateUpdate = true;
  18479. if (restart) {
  18480. this._updateParticlesSimulationRestart(time);
  18481. }
  18482. else {
  18483. this._isPaused = false;
  18484. this._updateParticles(time);
  18485. }
  18486. this.pause();
  18487. }
  18488. stop() {
  18489. this._burstsIndex = 0;
  18490. this._isEmitting = false;
  18491. this._emissionTime = 0;
  18492. }
  18493. cloneTo(destObject) {
  18494. var dest = destObject;
  18495. dest.duration = this.duration;
  18496. dest.looping = this.looping;
  18497. dest.prewarm = this.prewarm;
  18498. dest.startDelayType = this.startDelayType;
  18499. dest.startDelay = this.startDelay;
  18500. dest.startDelayMin = this.startDelayMin;
  18501. dest.startDelayMax = this.startDelayMax;
  18502. dest._maxStartLifetime = this._maxStartLifetime;
  18503. dest.startLifetimeType = this.startLifetimeType;
  18504. dest.startLifetimeConstant = this.startLifetimeConstant;
  18505. this.startLifeTimeGradient.cloneTo(dest.startLifeTimeGradient);
  18506. dest.startLifetimeConstantMin = this.startLifetimeConstantMin;
  18507. dest.startLifetimeConstantMax = this.startLifetimeConstantMax;
  18508. this.startLifeTimeGradientMin.cloneTo(dest.startLifeTimeGradientMin);
  18509. this.startLifeTimeGradientMax.cloneTo(dest.startLifeTimeGradientMax);
  18510. dest.startSpeedType = this.startSpeedType;
  18511. dest.startSpeedConstant = this.startSpeedConstant;
  18512. dest.startSpeedConstantMin = this.startSpeedConstantMin;
  18513. dest.startSpeedConstantMax = this.startSpeedConstantMax;
  18514. dest.threeDStartSize = this.threeDStartSize;
  18515. dest.startSizeType = this.startSizeType;
  18516. dest.startSizeConstant = this.startSizeConstant;
  18517. this.startSizeConstantSeparate.cloneTo(dest.startSizeConstantSeparate);
  18518. dest.startSizeConstantMin = this.startSizeConstantMin;
  18519. dest.startSizeConstantMax = this.startSizeConstantMax;
  18520. this.startSizeConstantMinSeparate.cloneTo(dest.startSizeConstantMinSeparate);
  18521. this.startSizeConstantMaxSeparate.cloneTo(dest.startSizeConstantMaxSeparate);
  18522. dest.threeDStartRotation = this.threeDStartRotation;
  18523. dest.startRotationType = this.startRotationType;
  18524. dest.startRotationConstant = this.startRotationConstant;
  18525. this.startRotationConstantSeparate.cloneTo(dest.startRotationConstantSeparate);
  18526. dest.startRotationConstantMin = this.startRotationConstantMin;
  18527. dest.startRotationConstantMax = this.startRotationConstantMax;
  18528. this.startRotationConstantMinSeparate.cloneTo(dest.startRotationConstantMinSeparate);
  18529. this.startRotationConstantMaxSeparate.cloneTo(dest.startRotationConstantMaxSeparate);
  18530. dest.randomizeRotationDirection = this.randomizeRotationDirection;
  18531. dest.startColorType = this.startColorType;
  18532. this.startColorConstant.cloneTo(dest.startColorConstant);
  18533. this.startColorConstantMin.cloneTo(dest.startColorConstantMin);
  18534. this.startColorConstantMax.cloneTo(dest.startColorConstantMax);
  18535. dest.gravityModifier = this.gravityModifier;
  18536. dest.simulationSpace = this.simulationSpace;
  18537. dest.scaleMode = this.scaleMode;
  18538. dest.playOnAwake = this.playOnAwake;
  18539. dest.autoRandomSeed = this.autoRandomSeed;
  18540. dest.randomSeed[0] = this.randomSeed[0];
  18541. dest.maxParticles = this.maxParticles;
  18542. (this._emission) && (dest._emission = this._emission.clone());
  18543. (this.shape) && (dest.shape = this.shape.clone());
  18544. (this.velocityOverLifetime) && (dest.velocityOverLifetime = this.velocityOverLifetime.clone());
  18545. (this.colorOverLifetime) && (dest.colorOverLifetime = this.colorOverLifetime.clone());
  18546. (this.sizeOverLifetime) && (dest.sizeOverLifetime = this.sizeOverLifetime.clone());
  18547. (this.rotationOverLifetime) && (dest.rotationOverLifetime = this.rotationOverLifetime.clone());
  18548. (this.textureSheetAnimation) && (dest.textureSheetAnimation = this.textureSheetAnimation.clone());
  18549. dest.isPerformanceMode = this.isPerformanceMode;
  18550. dest._isEmitting = this._isEmitting;
  18551. dest._isPlaying = this._isPlaying;
  18552. dest._isPaused = this._isPaused;
  18553. dest._playStartDelay = this._playStartDelay;
  18554. dest._frameRateTime = this._frameRateTime;
  18555. dest._emissionTime = this._emissionTime;
  18556. dest._totalDelayTime = this._totalDelayTime;
  18557. dest._burstsIndex = this._burstsIndex;
  18558. }
  18559. clone() {
  18560. var dest = new ShurikenParticleSystem(null);
  18561. this.cloneTo(dest);
  18562. return dest;
  18563. }
  18564. }
  18565. ShurikenParticleSystem._RANDOMOFFSET = new Uint32Array([0x23571a3e, 0xc34f56fe, 0x13371337, 0x12460f3b, 0x6aed452e, 0xdec4aea1, 0x96aa4de3, 0x8d2c8431, 0xf3857f6f, 0xe0fbd834, 0x13740583, 0x591bc05c, 0x40eb95e4, 0xbc524e5f, 0xaf502044, 0xa614b381, 0x1034e524, 0xfc524e5f]);
  18566. ShurikenParticleSystem.halfKSqrtOf2 = 1.42 * 0.5;
  18567. ShurikenParticleSystem._maxElapsedTime = 1.0 / 3.0;
  18568. ShurikenParticleSystem._tempVector30 = new Vector3();
  18569. ShurikenParticleSystem._tempVector31 = new Vector3();
  18570. ShurikenParticleSystem._tempVector32 = new Vector3();
  18571. ShurikenParticleSystem._tempVector33 = new Vector3();
  18572. ShurikenParticleSystem._tempVector34 = new Vector3();
  18573. ShurikenParticleSystem._tempVector35 = new Vector3();
  18574. ShurikenParticleSystem._tempVector36 = new Vector3();
  18575. ShurikenParticleSystem._tempVector37 = new Vector3();
  18576. ShurikenParticleSystem._tempVector38 = new Vector3();
  18577. ShurikenParticleSystem._tempVector39 = new Vector3();
  18578. ShurikenParticleSystem._tempPosition = new Vector3();
  18579. ShurikenParticleSystem._tempDirection = new Vector3();
  18580. ShurikenParticleSystem._type = GeometryElement._typeCounter++;
  18581. class Burst {
  18582. get time() {
  18583. return this._time;
  18584. }
  18585. get minCount() {
  18586. return this._minCount;
  18587. }
  18588. get maxCount() {
  18589. return this._maxCount;
  18590. }
  18591. constructor(time, minCount, maxCount) {
  18592. this._time = time;
  18593. this._minCount = minCount;
  18594. this._maxCount = maxCount;
  18595. }
  18596. cloneTo(destObject) {
  18597. var destBurst = destObject;
  18598. destBurst._time = this._time;
  18599. destBurst._minCount = this._minCount;
  18600. destBurst._maxCount = this._maxCount;
  18601. }
  18602. clone() {
  18603. var destBurst = new Burst(this._time, this._minCount, this._maxCount);
  18604. this.cloneTo(destBurst);
  18605. return destBurst;
  18606. }
  18607. }
  18608. class GradientColor {
  18609. constructor() {
  18610. this._type = 0;
  18611. this._constant = null;
  18612. this._constantMin = null;
  18613. this._constantMax = null;
  18614. this._gradient = null;
  18615. this._gradientMin = null;
  18616. this._gradientMax = null;
  18617. }
  18618. static createByConstant(constant) {
  18619. var gradientColor = new GradientColor();
  18620. gradientColor._type = 0;
  18621. gradientColor._constant = constant;
  18622. return gradientColor;
  18623. }
  18624. static createByGradient(gradient) {
  18625. var gradientColor = new GradientColor();
  18626. gradientColor._type = 1;
  18627. gradientColor._gradient = gradient;
  18628. return gradientColor;
  18629. }
  18630. static createByRandomTwoConstant(minConstant, maxConstant) {
  18631. var gradientColor = new GradientColor();
  18632. gradientColor._type = 2;
  18633. gradientColor._constantMin = minConstant;
  18634. gradientColor._constantMax = maxConstant;
  18635. return gradientColor;
  18636. }
  18637. static createByRandomTwoGradient(minGradient, maxGradient) {
  18638. var gradientColor = new GradientColor();
  18639. gradientColor._type = 3;
  18640. gradientColor._gradientMin = minGradient;
  18641. gradientColor._gradientMax = maxGradient;
  18642. return gradientColor;
  18643. }
  18644. get type() {
  18645. return this._type;
  18646. }
  18647. get constant() {
  18648. return this._constant;
  18649. }
  18650. get constantMin() {
  18651. return this._constantMin;
  18652. }
  18653. get constantMax() {
  18654. return this._constantMax;
  18655. }
  18656. get gradient() {
  18657. return this._gradient;
  18658. }
  18659. get gradientMin() {
  18660. return this._gradientMin;
  18661. }
  18662. get gradientMax() {
  18663. return this._gradientMax;
  18664. }
  18665. cloneTo(destObject) {
  18666. var destGradientColor = destObject;
  18667. destGradientColor._type = this._type;
  18668. this._constant.cloneTo(destGradientColor._constant);
  18669. this._constantMin.cloneTo(destGradientColor._constantMin);
  18670. this._constantMax.cloneTo(destGradientColor._constantMax);
  18671. this._gradient.cloneTo(destGradientColor._gradient);
  18672. this._gradientMin.cloneTo(destGradientColor._gradientMin);
  18673. this._gradientMax.cloneTo(destGradientColor._gradientMax);
  18674. }
  18675. clone() {
  18676. var destGradientColor = new GradientColor();
  18677. this.cloneTo(destGradientColor);
  18678. return destGradientColor;
  18679. }
  18680. }
  18681. class ColorOverLifetime {
  18682. get color() {
  18683. return this._color;
  18684. }
  18685. constructor(color) {
  18686. this._color = color;
  18687. }
  18688. cloneTo(destObject) {
  18689. var destColorOverLifetime = destObject;
  18690. this._color.cloneTo(destColorOverLifetime._color);
  18691. destColorOverLifetime.enbale = this.enbale;
  18692. }
  18693. clone() {
  18694. var destColor;
  18695. switch (this._color.type) {
  18696. case 0:
  18697. destColor = GradientColor.createByConstant(this._color.constant.clone());
  18698. break;
  18699. case 1:
  18700. destColor = GradientColor.createByGradient(this._color.gradient.clone());
  18701. break;
  18702. case 2:
  18703. destColor = GradientColor.createByRandomTwoConstant(this._color.constantMin.clone(), this._color.constantMax.clone());
  18704. break;
  18705. case 3:
  18706. destColor = GradientColor.createByRandomTwoGradient(this._color.gradientMin.clone(), this._color.gradientMax.clone());
  18707. break;
  18708. }
  18709. var destColorOverLifetime = new ColorOverLifetime(destColor);
  18710. destColorOverLifetime.enbale = this.enbale;
  18711. return destColorOverLifetime;
  18712. }
  18713. }
  18714. class FrameOverTime {
  18715. constructor() {
  18716. this._type = 0;
  18717. this._constant = 0;
  18718. this._overTime = null;
  18719. this._constantMin = 0;
  18720. this._constantMax = 0;
  18721. this._overTimeMin = null;
  18722. this._overTimeMax = null;
  18723. }
  18724. static createByConstant(constant) {
  18725. var rotationOverLifetime = new FrameOverTime();
  18726. rotationOverLifetime._type = 0;
  18727. rotationOverLifetime._constant = constant;
  18728. return rotationOverLifetime;
  18729. }
  18730. static createByOverTime(overTime) {
  18731. var rotationOverLifetime = new FrameOverTime();
  18732. rotationOverLifetime._type = 1;
  18733. rotationOverLifetime._overTime = overTime;
  18734. return rotationOverLifetime;
  18735. }
  18736. static createByRandomTwoConstant(constantMin, constantMax) {
  18737. var rotationOverLifetime = new FrameOverTime();
  18738. rotationOverLifetime._type = 2;
  18739. rotationOverLifetime._constantMin = constantMin;
  18740. rotationOverLifetime._constantMax = constantMax;
  18741. return rotationOverLifetime;
  18742. }
  18743. static createByRandomTwoOverTime(gradientFrameMin, gradientFrameMax) {
  18744. var rotationOverLifetime = new FrameOverTime();
  18745. rotationOverLifetime._type = 3;
  18746. rotationOverLifetime._overTimeMin = gradientFrameMin;
  18747. rotationOverLifetime._overTimeMax = gradientFrameMax;
  18748. return rotationOverLifetime;
  18749. }
  18750. get type() {
  18751. return this._type;
  18752. }
  18753. get constant() {
  18754. return this._constant;
  18755. }
  18756. get frameOverTimeData() {
  18757. return this._overTime;
  18758. }
  18759. get constantMin() {
  18760. return this._constantMin;
  18761. }
  18762. get constantMax() {
  18763. return this._constantMax;
  18764. }
  18765. get frameOverTimeDataMin() {
  18766. return this._overTimeMin;
  18767. }
  18768. get frameOverTimeDataMax() {
  18769. return this._overTimeMax;
  18770. }
  18771. cloneTo(destObject) {
  18772. var destFrameOverTime = destObject;
  18773. destFrameOverTime._type = this._type;
  18774. destFrameOverTime._constant = this._constant;
  18775. (this._overTime) && (this._overTime.cloneTo(destFrameOverTime._overTime));
  18776. destFrameOverTime._constantMin = this._constantMin;
  18777. destFrameOverTime._constantMax = this._constantMax;
  18778. (this._overTimeMin) && (this._overTimeMin.cloneTo(destFrameOverTime._overTimeMin));
  18779. (this._overTimeMax) && (this._overTimeMax.cloneTo(destFrameOverTime._overTimeMax));
  18780. }
  18781. clone() {
  18782. var destFrameOverTime = new FrameOverTime();
  18783. this.cloneTo(destFrameOverTime);
  18784. return destFrameOverTime;
  18785. }
  18786. }
  18787. class GradientAngularVelocity {
  18788. constructor() {
  18789. this._type = 0;
  18790. this._separateAxes = false;
  18791. this._constant = 0;
  18792. this._constantSeparate = null;
  18793. this._gradient = null;
  18794. this._gradientX = null;
  18795. this._gradientY = null;
  18796. this._gradientZ = null;
  18797. this._gradientW = null;
  18798. this._constantMin = 0;
  18799. this._constantMax = 0;
  18800. this._constantMinSeparate = null;
  18801. this._constantMaxSeparate = null;
  18802. this._gradientMin = null;
  18803. this._gradientMax = null;
  18804. this._gradientXMin = null;
  18805. this._gradientXMax = null;
  18806. this._gradientYMin = null;
  18807. this._gradientYMax = null;
  18808. this._gradientZMin = null;
  18809. this._gradientZMax = null;
  18810. this._gradientWMin = null;
  18811. this._gradientWMax = null;
  18812. }
  18813. static createByConstant(constant) {
  18814. var gradientAngularVelocity = new GradientAngularVelocity();
  18815. gradientAngularVelocity._type = 0;
  18816. gradientAngularVelocity._separateAxes = false;
  18817. gradientAngularVelocity._constant = constant;
  18818. return gradientAngularVelocity;
  18819. }
  18820. static createByConstantSeparate(separateConstant) {
  18821. var gradientAngularVelocity = new GradientAngularVelocity();
  18822. gradientAngularVelocity._type = 0;
  18823. gradientAngularVelocity._separateAxes = true;
  18824. gradientAngularVelocity._constantSeparate = separateConstant;
  18825. return gradientAngularVelocity;
  18826. }
  18827. static createByGradient(gradient) {
  18828. var gradientAngularVelocity = new GradientAngularVelocity();
  18829. gradientAngularVelocity._type = 1;
  18830. gradientAngularVelocity._separateAxes = false;
  18831. gradientAngularVelocity._gradient = gradient;
  18832. return gradientAngularVelocity;
  18833. }
  18834. static createByGradientSeparate(gradientX, gradientY, gradientZ) {
  18835. var gradientAngularVelocity = new GradientAngularVelocity();
  18836. gradientAngularVelocity._type = 1;
  18837. gradientAngularVelocity._separateAxes = true;
  18838. gradientAngularVelocity._gradientX = gradientX;
  18839. gradientAngularVelocity._gradientY = gradientY;
  18840. gradientAngularVelocity._gradientZ = gradientZ;
  18841. return gradientAngularVelocity;
  18842. }
  18843. static createByRandomTwoConstant(constantMin, constantMax) {
  18844. var gradientAngularVelocity = new GradientAngularVelocity();
  18845. gradientAngularVelocity._type = 2;
  18846. gradientAngularVelocity._separateAxes = false;
  18847. gradientAngularVelocity._constantMin = constantMin;
  18848. gradientAngularVelocity._constantMax = constantMax;
  18849. return gradientAngularVelocity;
  18850. }
  18851. static createByRandomTwoConstantSeparate(separateConstantMin, separateConstantMax) {
  18852. var gradientAngularVelocity = new GradientAngularVelocity();
  18853. gradientAngularVelocity._type = 2;
  18854. gradientAngularVelocity._separateAxes = true;
  18855. gradientAngularVelocity._constantMinSeparate = separateConstantMin;
  18856. gradientAngularVelocity._constantMaxSeparate = separateConstantMax;
  18857. return gradientAngularVelocity;
  18858. }
  18859. static createByRandomTwoGradient(gradientMin, gradientMax) {
  18860. var gradientAngularVelocity = new GradientAngularVelocity();
  18861. gradientAngularVelocity._type = 3;
  18862. gradientAngularVelocity._separateAxes = false;
  18863. gradientAngularVelocity._gradientMin = gradientMin;
  18864. gradientAngularVelocity._gradientMax = gradientMax;
  18865. return gradientAngularVelocity;
  18866. }
  18867. static createByRandomTwoGradientSeparate(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax, gradientWMin, gradientWMax) {
  18868. var gradientAngularVelocity = new GradientAngularVelocity();
  18869. gradientAngularVelocity._type = 3;
  18870. gradientAngularVelocity._separateAxes = true;
  18871. gradientAngularVelocity._gradientXMin = gradientXMin;
  18872. gradientAngularVelocity._gradientXMax = gradientXMax;
  18873. gradientAngularVelocity._gradientYMin = gradientYMin;
  18874. gradientAngularVelocity._gradientYMax = gradientYMax;
  18875. gradientAngularVelocity._gradientZMin = gradientZMin;
  18876. gradientAngularVelocity._gradientZMax = gradientZMax;
  18877. gradientAngularVelocity._gradientWMin = gradientWMin;
  18878. gradientAngularVelocity._gradientWMax = gradientWMax;
  18879. return gradientAngularVelocity;
  18880. }
  18881. get type() {
  18882. return this._type;
  18883. }
  18884. get separateAxes() {
  18885. return this._separateAxes;
  18886. }
  18887. get constant() {
  18888. return this._constant;
  18889. }
  18890. get constantSeparate() {
  18891. return this._constantSeparate;
  18892. }
  18893. get gradient() {
  18894. return this._gradient;
  18895. }
  18896. get gradientX() {
  18897. return this._gradientX;
  18898. }
  18899. get gradientY() {
  18900. return this._gradientY;
  18901. }
  18902. get gradientZ() {
  18903. return this._gradientZ;
  18904. }
  18905. get gradientW() {
  18906. return this._gradientW;
  18907. }
  18908. get constantMin() {
  18909. return this._constantMin;
  18910. }
  18911. get constantMax() {
  18912. return this._constantMax;
  18913. }
  18914. get constantMinSeparate() {
  18915. return this._constantMinSeparate;
  18916. }
  18917. get constantMaxSeparate() {
  18918. return this._constantMaxSeparate;
  18919. }
  18920. get gradientMin() {
  18921. return this._gradientMin;
  18922. }
  18923. get gradientMax() {
  18924. return this._gradientMax;
  18925. }
  18926. get gradientXMin() {
  18927. return this._gradientXMin;
  18928. }
  18929. get gradientXMax() {
  18930. return this._gradientXMax;
  18931. }
  18932. get gradientYMin() {
  18933. return this._gradientYMin;
  18934. }
  18935. get gradientYMax() {
  18936. return this._gradientYMax;
  18937. }
  18938. get gradientZMin() {
  18939. return this._gradientZMin;
  18940. }
  18941. get gradientZMax() {
  18942. return this._gradientZMax;
  18943. }
  18944. get gradientWMin() {
  18945. return this._gradientWMin;
  18946. }
  18947. get gradientWMax() {
  18948. return this._gradientWMax;
  18949. }
  18950. cloneTo(destObject) {
  18951. var destGradientAngularVelocity = destObject;
  18952. destGradientAngularVelocity._type = this._type;
  18953. destGradientAngularVelocity._separateAxes = this._separateAxes;
  18954. destGradientAngularVelocity._constant = this._constant;
  18955. this._constantSeparate.cloneTo(destGradientAngularVelocity._constantSeparate);
  18956. this._gradient.cloneTo(destGradientAngularVelocity._gradient);
  18957. this._gradientX.cloneTo(destGradientAngularVelocity._gradientX);
  18958. this._gradientY.cloneTo(destGradientAngularVelocity._gradientY);
  18959. this._gradientZ.cloneTo(destGradientAngularVelocity._gradientZ);
  18960. destGradientAngularVelocity._constantMin = this._constantMin;
  18961. destGradientAngularVelocity._constantMax = this._constantMax;
  18962. this._constantMinSeparate.cloneTo(destGradientAngularVelocity._constantMinSeparate);
  18963. this._constantMaxSeparate.cloneTo(destGradientAngularVelocity._constantMaxSeparate);
  18964. this._gradientMin.cloneTo(destGradientAngularVelocity._gradientMin);
  18965. this._gradientMax.cloneTo(destGradientAngularVelocity._gradientMax);
  18966. this._gradientXMin.cloneTo(destGradientAngularVelocity._gradientXMin);
  18967. this._gradientXMax.cloneTo(destGradientAngularVelocity._gradientXMax);
  18968. this._gradientYMin.cloneTo(destGradientAngularVelocity._gradientYMin);
  18969. this._gradientYMax.cloneTo(destGradientAngularVelocity._gradientYMax);
  18970. this._gradientZMin.cloneTo(destGradientAngularVelocity._gradientZMin);
  18971. this._gradientZMax.cloneTo(destGradientAngularVelocity._gradientZMax);
  18972. }
  18973. clone() {
  18974. var destGradientAngularVelocity = new GradientAngularVelocity();
  18975. this.cloneTo(destGradientAngularVelocity);
  18976. return destGradientAngularVelocity;
  18977. }
  18978. }
  18979. class GradientDataInt {
  18980. constructor() {
  18981. this._currentLength = 0;
  18982. this._elements = new Float32Array(8);
  18983. }
  18984. get gradientCount() {
  18985. return this._currentLength / 2;
  18986. }
  18987. add(key, value) {
  18988. if (this._currentLength < 8) {
  18989. if ((this._currentLength === 6) && ((key !== 1))) {
  18990. key = 1;
  18991. console.log("Warning:the forth key is be force set to 1.");
  18992. }
  18993. this._elements[this._currentLength++] = key;
  18994. this._elements[this._currentLength++] = value;
  18995. }
  18996. else {
  18997. console.log("Warning:data count must lessEqual than 4");
  18998. }
  18999. }
  19000. cloneTo(destObject) {
  19001. var destGradientDataInt = destObject;
  19002. destGradientDataInt._currentLength = this._currentLength;
  19003. var destElements = destGradientDataInt._elements;
  19004. for (var i = 0, n = this._elements.length; i < n; i++) {
  19005. destElements[i] = this._elements[i];
  19006. }
  19007. }
  19008. clone() {
  19009. var destGradientDataInt = new GradientDataInt();
  19010. this.cloneTo(destGradientDataInt);
  19011. return destGradientDataInt;
  19012. }
  19013. }
  19014. class GradientSize {
  19015. constructor() {
  19016. this._type = 0;
  19017. this._separateAxes = false;
  19018. this._gradient = null;
  19019. this._gradientX = null;
  19020. this._gradientY = null;
  19021. this._gradientZ = null;
  19022. this._constantMin = 0;
  19023. this._constantMax = 0;
  19024. this._constantMinSeparate = null;
  19025. this._constantMaxSeparate = null;
  19026. this._gradientMin = null;
  19027. this._gradientMax = null;
  19028. this._gradientXMin = null;
  19029. this._gradientXMax = null;
  19030. this._gradientYMin = null;
  19031. this._gradientYMax = null;
  19032. this._gradientZMin = null;
  19033. this._gradientZMax = null;
  19034. }
  19035. static createByGradient(gradient) {
  19036. var gradientSize = new GradientSize();
  19037. gradientSize._type = 0;
  19038. gradientSize._separateAxes = false;
  19039. gradientSize._gradient = gradient;
  19040. return gradientSize;
  19041. }
  19042. static createByGradientSeparate(gradientX, gradientY, gradientZ) {
  19043. var gradientSize = new GradientSize();
  19044. gradientSize._type = 0;
  19045. gradientSize._separateAxes = true;
  19046. gradientSize._gradientX = gradientX;
  19047. gradientSize._gradientY = gradientY;
  19048. gradientSize._gradientZ = gradientZ;
  19049. return gradientSize;
  19050. }
  19051. static createByRandomTwoConstant(constantMin, constantMax) {
  19052. var gradientSize = new GradientSize();
  19053. gradientSize._type = 1;
  19054. gradientSize._separateAxes = false;
  19055. gradientSize._constantMin = constantMin;
  19056. gradientSize._constantMax = constantMax;
  19057. return gradientSize;
  19058. }
  19059. static createByRandomTwoConstantSeparate(constantMinSeparate, constantMaxSeparate) {
  19060. var gradientSize = new GradientSize();
  19061. gradientSize._type = 1;
  19062. gradientSize._separateAxes = true;
  19063. gradientSize._constantMinSeparate = constantMinSeparate;
  19064. gradientSize._constantMaxSeparate = constantMaxSeparate;
  19065. return gradientSize;
  19066. }
  19067. static createByRandomTwoGradient(gradientMin, gradientMax) {
  19068. var gradientSize = new GradientSize();
  19069. gradientSize._type = 2;
  19070. gradientSize._separateAxes = false;
  19071. gradientSize._gradientMin = gradientMin;
  19072. gradientSize._gradientMax = gradientMax;
  19073. return gradientSize;
  19074. }
  19075. static createByRandomTwoGradientSeparate(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax) {
  19076. var gradientSize = new GradientSize();
  19077. gradientSize._type = 2;
  19078. gradientSize._separateAxes = true;
  19079. gradientSize._gradientXMin = gradientXMin;
  19080. gradientSize._gradientXMax = gradientXMax;
  19081. gradientSize._gradientYMin = gradientYMin;
  19082. gradientSize._gradientYMax = gradientYMax;
  19083. gradientSize._gradientZMin = gradientZMin;
  19084. gradientSize._gradientZMax = gradientZMax;
  19085. return gradientSize;
  19086. }
  19087. get type() {
  19088. return this._type;
  19089. }
  19090. get separateAxes() {
  19091. return this._separateAxes;
  19092. }
  19093. get gradient() {
  19094. return this._gradient;
  19095. }
  19096. get gradientX() {
  19097. return this._gradientX;
  19098. }
  19099. get gradientY() {
  19100. return this._gradientY;
  19101. }
  19102. get gradientZ() {
  19103. return this._gradientZ;
  19104. }
  19105. get constantMin() {
  19106. return this._constantMin;
  19107. }
  19108. get constantMax() {
  19109. return this._constantMax;
  19110. }
  19111. get constantMinSeparate() {
  19112. return this._constantMinSeparate;
  19113. }
  19114. get constantMaxSeparate() {
  19115. return this._constantMaxSeparate;
  19116. }
  19117. get gradientMin() {
  19118. return this._gradientMin;
  19119. }
  19120. get gradientMax() {
  19121. return this._gradientMax;
  19122. }
  19123. get gradientXMin() {
  19124. return this._gradientXMin;
  19125. }
  19126. get gradientXMax() {
  19127. return this._gradientXMax;
  19128. }
  19129. get gradientYMin() {
  19130. return this._gradientYMin;
  19131. }
  19132. get gradientYMax() {
  19133. return this._gradientYMax;
  19134. }
  19135. get gradientZMin() {
  19136. return this._gradientZMin;
  19137. }
  19138. get gradientZMax() {
  19139. return this._gradientZMax;
  19140. }
  19141. getMaxSizeInGradient() {
  19142. var i, n;
  19143. var maxSize = -Number.MAX_VALUE;
  19144. switch (this._type) {
  19145. case 0:
  19146. if (this._separateAxes) {
  19147. for (i = 0, n = this._gradientX.gradientCount; i < n; i++)
  19148. maxSize = Math.max(maxSize, this._gradientX.getValueByIndex(i));
  19149. for (i = 0, n = this._gradientY.gradientCount; i < n; i++)
  19150. maxSize = Math.max(maxSize, this._gradientY.getValueByIndex(i));
  19151. }
  19152. else {
  19153. for (i = 0, n = this._gradient.gradientCount; i < n; i++)
  19154. maxSize = Math.max(maxSize, this._gradient.getValueByIndex(i));
  19155. }
  19156. break;
  19157. case 1:
  19158. if (this._separateAxes) {
  19159. maxSize = Math.max(this._constantMinSeparate.x, this._constantMaxSeparate.x);
  19160. maxSize = Math.max(maxSize, this._constantMinSeparate.y);
  19161. maxSize = Math.max(maxSize, this._constantMaxSeparate.y);
  19162. }
  19163. else {
  19164. maxSize = Math.max(this._constantMin, this._constantMax);
  19165. }
  19166. break;
  19167. case 2:
  19168. if (this._separateAxes) {
  19169. for (i = 0, n = this._gradientXMin.gradientCount; i < n; i++)
  19170. maxSize = Math.max(maxSize, this._gradientXMin.getValueByIndex(i));
  19171. for (i = 0, n = this._gradientXMax.gradientCount; i < n; i++)
  19172. maxSize = Math.max(maxSize, this._gradientXMax.getValueByIndex(i));
  19173. for (i = 0, n = this._gradientYMin.gradientCount; i < n; i++)
  19174. maxSize = Math.max(maxSize, this._gradientYMin.getValueByIndex(i));
  19175. for (i = 0, n = this._gradientZMax.gradientCount; i < n; i++)
  19176. maxSize = Math.max(maxSize, this._gradientZMax.getValueByIndex(i));
  19177. }
  19178. else {
  19179. for (i = 0, n = this._gradientMin.gradientCount; i < n; i++)
  19180. maxSize = Math.max(maxSize, this._gradientMin.getValueByIndex(i));
  19181. for (i = 0, n = this._gradientMax.gradientCount; i < n; i++)
  19182. maxSize = Math.max(maxSize, this._gradientMax.getValueByIndex(i));
  19183. }
  19184. break;
  19185. }
  19186. return maxSize;
  19187. }
  19188. cloneTo(destObject) {
  19189. var destGradientSize = destObject;
  19190. destGradientSize._type = this._type;
  19191. destGradientSize._separateAxes = this._separateAxes;
  19192. this._gradient.cloneTo(destGradientSize._gradient);
  19193. this._gradientX.cloneTo(destGradientSize._gradientX);
  19194. this._gradientY.cloneTo(destGradientSize._gradientY);
  19195. this._gradientZ.cloneTo(destGradientSize._gradientZ);
  19196. destGradientSize._constantMin = this._constantMin;
  19197. destGradientSize._constantMax = this._constantMax;
  19198. this._constantMinSeparate.cloneTo(destGradientSize._constantMinSeparate);
  19199. this._constantMaxSeparate.cloneTo(destGradientSize._constantMaxSeparate);
  19200. this._gradientMin.cloneTo(destGradientSize._gradientMin);
  19201. this._gradientMax.cloneTo(destGradientSize._gradientMax);
  19202. this._gradientXMin.cloneTo(destGradientSize._gradientXMin);
  19203. this._gradientXMax.cloneTo(destGradientSize._gradientXMax);
  19204. this._gradientYMin.cloneTo(destGradientSize._gradientYMin);
  19205. this._gradientYMax.cloneTo(destGradientSize._gradientYMax);
  19206. this._gradientZMin.cloneTo(destGradientSize._gradientZMin);
  19207. this._gradientZMax.cloneTo(destGradientSize._gradientZMax);
  19208. }
  19209. clone() {
  19210. var destGradientSize = new GradientSize();
  19211. this.cloneTo(destGradientSize);
  19212. return destGradientSize;
  19213. }
  19214. }
  19215. class GradientVelocity {
  19216. constructor() {
  19217. this._type = 0;
  19218. this._constant = null;
  19219. this._gradientX = null;
  19220. this._gradientY = null;
  19221. this._gradientZ = null;
  19222. this._constantMin = null;
  19223. this._constantMax = null;
  19224. this._gradientXMin = null;
  19225. this._gradientXMax = null;
  19226. this._gradientYMin = null;
  19227. this._gradientYMax = null;
  19228. this._gradientZMin = null;
  19229. this._gradientZMax = null;
  19230. }
  19231. static createByConstant(constant) {
  19232. var gradientVelocity = new GradientVelocity();
  19233. gradientVelocity._type = 0;
  19234. gradientVelocity._constant = constant;
  19235. return gradientVelocity;
  19236. }
  19237. static createByGradient(gradientX, gradientY, gradientZ) {
  19238. var gradientVelocity = new GradientVelocity();
  19239. gradientVelocity._type = 1;
  19240. gradientVelocity._gradientX = gradientX;
  19241. gradientVelocity._gradientY = gradientY;
  19242. gradientVelocity._gradientZ = gradientZ;
  19243. return gradientVelocity;
  19244. }
  19245. static createByRandomTwoConstant(constantMin, constantMax) {
  19246. var gradientVelocity = new GradientVelocity();
  19247. gradientVelocity._type = 2;
  19248. gradientVelocity._constantMin = constantMin;
  19249. gradientVelocity._constantMax = constantMax;
  19250. return gradientVelocity;
  19251. }
  19252. static createByRandomTwoGradient(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax) {
  19253. var gradientVelocity = new GradientVelocity();
  19254. gradientVelocity._type = 3;
  19255. gradientVelocity._gradientXMin = gradientXMin;
  19256. gradientVelocity._gradientXMax = gradientXMax;
  19257. gradientVelocity._gradientYMin = gradientYMin;
  19258. gradientVelocity._gradientYMax = gradientYMax;
  19259. gradientVelocity._gradientZMin = gradientZMin;
  19260. gradientVelocity._gradientZMax = gradientZMax;
  19261. return gradientVelocity;
  19262. }
  19263. get type() {
  19264. return this._type;
  19265. }
  19266. get constant() {
  19267. return this._constant;
  19268. }
  19269. get gradientX() {
  19270. return this._gradientX;
  19271. }
  19272. get gradientY() {
  19273. return this._gradientY;
  19274. }
  19275. get gradientZ() {
  19276. return this._gradientZ;
  19277. }
  19278. get constantMin() {
  19279. return this._constantMin;
  19280. }
  19281. get constantMax() {
  19282. return this._constantMax;
  19283. }
  19284. get gradientXMin() {
  19285. return this._gradientXMin;
  19286. }
  19287. get gradientXMax() {
  19288. return this._gradientXMax;
  19289. }
  19290. get gradientYMin() {
  19291. return this._gradientYMin;
  19292. }
  19293. get gradientYMax() {
  19294. return this._gradientYMax;
  19295. }
  19296. get gradientZMin() {
  19297. return this._gradientZMin;
  19298. }
  19299. get gradientZMax() {
  19300. return this._gradientZMax;
  19301. }
  19302. cloneTo(destObject) {
  19303. var destGradientVelocity = destObject;
  19304. destGradientVelocity._type = this._type;
  19305. this._constant.cloneTo(destGradientVelocity._constant);
  19306. this._gradientX.cloneTo(destGradientVelocity._gradientX);
  19307. this._gradientY.cloneTo(destGradientVelocity._gradientY);
  19308. this._gradientZ.cloneTo(destGradientVelocity._gradientZ);
  19309. this._constantMin.cloneTo(destGradientVelocity._constantMin);
  19310. this._constantMax.cloneTo(destGradientVelocity._constantMax);
  19311. this._gradientXMin.cloneTo(destGradientVelocity._gradientXMin);
  19312. this._gradientXMax.cloneTo(destGradientVelocity._gradientXMax);
  19313. this._gradientYMin.cloneTo(destGradientVelocity._gradientYMin);
  19314. this._gradientYMax.cloneTo(destGradientVelocity._gradientYMax);
  19315. this._gradientZMin.cloneTo(destGradientVelocity._gradientZMin);
  19316. this._gradientZMax.cloneTo(destGradientVelocity._gradientZMax);
  19317. }
  19318. clone() {
  19319. var destGradientVelocity = new GradientVelocity();
  19320. this.cloneTo(destGradientVelocity);
  19321. return destGradientVelocity;
  19322. }
  19323. }
  19324. class RotationOverLifetime {
  19325. get angularVelocity() {
  19326. return this._angularVelocity;
  19327. }
  19328. constructor(angularVelocity) {
  19329. this._angularVelocity = angularVelocity;
  19330. }
  19331. cloneTo(destObject) {
  19332. var destRotationOverLifetime = destObject;
  19333. this._angularVelocity.cloneTo(destRotationOverLifetime._angularVelocity);
  19334. destRotationOverLifetime.enbale = this.enbale;
  19335. }
  19336. clone() {
  19337. var destAngularVelocity;
  19338. switch (this._angularVelocity.type) {
  19339. case 0:
  19340. if (this._angularVelocity.separateAxes)
  19341. destAngularVelocity = GradientAngularVelocity.createByConstantSeparate(this._angularVelocity.constantSeparate.clone());
  19342. else
  19343. destAngularVelocity = GradientAngularVelocity.createByConstant(this._angularVelocity.constant);
  19344. break;
  19345. case 1:
  19346. if (this._angularVelocity.separateAxes)
  19347. destAngularVelocity = GradientAngularVelocity.createByGradientSeparate(this._angularVelocity.gradientX.clone(), this._angularVelocity.gradientY.clone(), this._angularVelocity.gradientZ.clone());
  19348. else
  19349. destAngularVelocity = GradientAngularVelocity.createByGradient(this._angularVelocity.gradient.clone());
  19350. break;
  19351. case 2:
  19352. if (this._angularVelocity.separateAxes)
  19353. destAngularVelocity = GradientAngularVelocity.createByRandomTwoConstantSeparate(this._angularVelocity.constantMinSeparate.clone(), this._angularVelocity.constantMaxSeparate.clone());
  19354. else
  19355. destAngularVelocity = GradientAngularVelocity.createByRandomTwoConstant(this._angularVelocity.constantMin, this._angularVelocity.constantMax);
  19356. break;
  19357. case 3:
  19358. if (this._angularVelocity.separateAxes)
  19359. 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());
  19360. else
  19361. destAngularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._angularVelocity.gradientMin.clone(), this._angularVelocity.gradientMax.clone());
  19362. break;
  19363. }
  19364. var destRotationOverLifetime = new RotationOverLifetime(destAngularVelocity);
  19365. destRotationOverLifetime.enbale = this.enbale;
  19366. return destRotationOverLifetime;
  19367. }
  19368. }
  19369. class BaseShape {
  19370. constructor() {
  19371. }
  19372. _getShapeBoundBox(boundBox) {
  19373. throw new Error("BaseShape: must override it.");
  19374. }
  19375. _getSpeedBoundBox(boundBox) {
  19376. throw new Error("BaseShape: must override it.");
  19377. }
  19378. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  19379. throw new Error("BaseShape: must override it.");
  19380. }
  19381. _calculateProceduralBounds(boundBox, emitterPosScale, minMaxBounds) {
  19382. this._getShapeBoundBox(boundBox);
  19383. var min = boundBox.min;
  19384. var max = boundBox.max;
  19385. Vector3.multiply(min, emitterPosScale, min);
  19386. Vector3.multiply(max, emitterPosScale, max);
  19387. var speedBounds = new BoundBox(new Vector3(), new Vector3());
  19388. if (this.randomDirection) {
  19389. speedBounds.min = new Vector3(-1, -1, -1);
  19390. speedBounds.max = new Vector3(1, 1, 1);
  19391. }
  19392. else {
  19393. this._getSpeedBoundBox(speedBounds);
  19394. }
  19395. var maxSpeedBound = new BoundBox(new Vector3(), new Vector3());
  19396. var maxSpeedMin = maxSpeedBound.min;
  19397. var maxSpeedMax = maxSpeedBound.max;
  19398. Vector3.scale(speedBounds.min, minMaxBounds.y, maxSpeedMin);
  19399. Vector3.scale(speedBounds.max, minMaxBounds.y, maxSpeedMax);
  19400. Vector3.add(boundBox.min, maxSpeedMin, maxSpeedMin);
  19401. Vector3.add(boundBox.max, maxSpeedMax, maxSpeedMax);
  19402. Vector3.min(boundBox.min, maxSpeedMin, boundBox.min);
  19403. Vector3.max(boundBox.max, maxSpeedMin, boundBox.max);
  19404. var minSpeedBound = new BoundBox(new Vector3(), new Vector3());
  19405. var minSpeedMin = minSpeedBound.min;
  19406. var minSpeedMax = minSpeedBound.max;
  19407. Vector3.scale(speedBounds.min, minMaxBounds.x, minSpeedMin);
  19408. Vector3.scale(speedBounds.max, minMaxBounds.x, minSpeedMax);
  19409. Vector3.min(minSpeedBound.min, minSpeedMax, maxSpeedMin);
  19410. Vector3.max(minSpeedBound.min, minSpeedMax, maxSpeedMax);
  19411. Vector3.min(boundBox.min, maxSpeedMin, boundBox.min);
  19412. Vector3.max(boundBox.max, maxSpeedMin, boundBox.max);
  19413. }
  19414. cloneTo(destObject) {
  19415. var destShape = destObject;
  19416. destShape.enable = this.enable;
  19417. }
  19418. clone() {
  19419. var destShape = new BaseShape();
  19420. this.cloneTo(destShape);
  19421. return destShape;
  19422. }
  19423. }
  19424. class ShapeUtils {
  19425. static _randomPointUnitArcCircle(arc, out, rand = null) {
  19426. var angle;
  19427. if (rand)
  19428. angle = rand.getFloat() * arc;
  19429. else
  19430. angle = Math.random() * arc;
  19431. out.x = Math.cos(angle);
  19432. out.y = Math.sin(angle);
  19433. }
  19434. static _randomPointInsideUnitArcCircle(arc, out, rand = null) {
  19435. ShapeUtils._randomPointUnitArcCircle(arc, out, rand);
  19436. var range;
  19437. if (rand)
  19438. range = Math.pow(rand.getFloat(), 1.0 / 2.0);
  19439. else
  19440. range = Math.pow(Math.random(), 1.0 / 2.0);
  19441. out.x = out.x * range;
  19442. out.y = out.y * range;
  19443. }
  19444. static _randomPointUnitCircle(out, rand = null) {
  19445. var angle;
  19446. if (rand)
  19447. angle = rand.getFloat() * Math.PI * 2;
  19448. else
  19449. angle = Math.random() * Math.PI * 2;
  19450. out.x = Math.cos(angle);
  19451. out.y = Math.sin(angle);
  19452. }
  19453. static _randomPointInsideUnitCircle(out, rand = null) {
  19454. ShapeUtils._randomPointUnitCircle(out);
  19455. var range;
  19456. if (rand)
  19457. range = Math.pow(rand.getFloat(), 1.0 / 2.0);
  19458. else
  19459. range = Math.pow(Math.random(), 1.0 / 2.0);
  19460. out.x = out.x * range;
  19461. out.y = out.y * range;
  19462. }
  19463. static _randomPointUnitSphere(out, rand = null) {
  19464. var z;
  19465. var a;
  19466. if (rand) {
  19467. z = out.z = rand.getFloat() * 2 - 1.0;
  19468. a = rand.getFloat() * Math.PI * 2;
  19469. }
  19470. else {
  19471. z = out.z = Math.random() * 2 - 1.0;
  19472. a = Math.random() * Math.PI * 2;
  19473. }
  19474. var r = Math.sqrt(1.0 - z * z);
  19475. out.x = r * Math.cos(a);
  19476. out.y = r * Math.sin(a);
  19477. }
  19478. static _randomPointInsideUnitSphere(out, rand = null) {
  19479. ShapeUtils._randomPointUnitSphere(out);
  19480. var range;
  19481. if (rand)
  19482. range = Math.pow(rand.getFloat(), 1.0 / 3.0);
  19483. else
  19484. range = Math.pow(Math.random(), 1.0 / 3.0);
  19485. out.x = out.x * range;
  19486. out.y = out.y * range;
  19487. out.z = out.z * range;
  19488. }
  19489. static _randomPointInsideHalfUnitBox(out, rand = null) {
  19490. if (rand) {
  19491. out.x = (rand.getFloat() - 0.5);
  19492. out.y = (rand.getFloat() - 0.5);
  19493. out.z = (rand.getFloat() - 0.5);
  19494. }
  19495. else {
  19496. out.x = (Math.random() - 0.5);
  19497. out.y = (Math.random() - 0.5);
  19498. out.z = (Math.random() - 0.5);
  19499. }
  19500. }
  19501. constructor() {
  19502. }
  19503. }
  19504. class BoxShape extends BaseShape {
  19505. constructor() {
  19506. super();
  19507. this.x = 1.0;
  19508. this.y = 1.0;
  19509. this.z = 1.0;
  19510. this.randomDirection = false;
  19511. }
  19512. _getShapeBoundBox(boundBox) {
  19513. var min = boundBox.min;
  19514. min.x = -this.x * 0.5;
  19515. min.y = -this.y * 0.5;
  19516. min.z = -this.z * 0.5;
  19517. var max = boundBox.max;
  19518. max.x = this.x * 0.5;
  19519. max.y = this.y * 0.5;
  19520. max.z = this.z * 0.5;
  19521. }
  19522. _getSpeedBoundBox(boundBox) {
  19523. var min = boundBox.min;
  19524. min.x = 0.0;
  19525. min.y = 0.0;
  19526. min.z = 0.0;
  19527. var max = boundBox.max;
  19528. max.x = 0.0;
  19529. max.y = 1.0;
  19530. max.z = 0.0;
  19531. }
  19532. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  19533. if (rand) {
  19534. rand.seed = randomSeeds[16];
  19535. ShapeUtils._randomPointInsideHalfUnitBox(position, rand);
  19536. randomSeeds[16] = rand.seed;
  19537. }
  19538. else {
  19539. ShapeUtils._randomPointInsideHalfUnitBox(position);
  19540. }
  19541. position.x = this.x * position.x;
  19542. position.y = this.y * position.y;
  19543. position.z = this.z * position.z;
  19544. if (this.randomDirection) {
  19545. if (rand) {
  19546. rand.seed = randomSeeds[17];
  19547. ShapeUtils._randomPointUnitSphere(direction, rand);
  19548. randomSeeds[17] = rand.seed;
  19549. }
  19550. else {
  19551. ShapeUtils._randomPointUnitSphere(direction);
  19552. }
  19553. }
  19554. else {
  19555. direction.x = 0.0;
  19556. direction.y = 0.0;
  19557. direction.z = 1.0;
  19558. }
  19559. }
  19560. cloneTo(destObject) {
  19561. super.cloneTo(destObject);
  19562. var destShape = destObject;
  19563. destShape.x = this.x;
  19564. destShape.y = this.y;
  19565. destShape.z = this.z;
  19566. destShape.randomDirection = this.randomDirection;
  19567. }
  19568. clone() {
  19569. var destShape = new BoxShape();
  19570. this.cloneTo(destShape);
  19571. return destShape;
  19572. }
  19573. }
  19574. class CircleShape extends BaseShape {
  19575. constructor() {
  19576. super();
  19577. this.radius = 1.0;
  19578. this.arc = 360.0 / 180.0 * Math.PI;
  19579. this.emitFromEdge = false;
  19580. this.randomDirection = false;
  19581. }
  19582. _getShapeBoundBox(boundBox) {
  19583. var min = boundBox.min;
  19584. min.x = min.z = -this.radius;
  19585. min.y = 0;
  19586. var max = boundBox.max;
  19587. max.x = max.z = this.radius;
  19588. max.y = 0;
  19589. }
  19590. _getSpeedBoundBox(boundBox) {
  19591. var min = boundBox.min;
  19592. min.x = min.y = -1;
  19593. min.z = 0;
  19594. var max = boundBox.max;
  19595. max.x = max.y = 1;
  19596. max.z = 0;
  19597. }
  19598. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  19599. var positionPoint = CircleShape._tempPositionPoint;
  19600. if (rand) {
  19601. rand.seed = randomSeeds[16];
  19602. if (this.emitFromEdge)
  19603. ShapeUtils._randomPointUnitArcCircle(this.arc, CircleShape._tempPositionPoint, rand);
  19604. else
  19605. ShapeUtils._randomPointInsideUnitArcCircle(this.arc, CircleShape._tempPositionPoint, rand);
  19606. randomSeeds[16] = rand.seed;
  19607. }
  19608. else {
  19609. if (this.emitFromEdge)
  19610. ShapeUtils._randomPointUnitArcCircle(this.arc, CircleShape._tempPositionPoint);
  19611. else
  19612. ShapeUtils._randomPointInsideUnitArcCircle(this.arc, CircleShape._tempPositionPoint);
  19613. }
  19614. position.x = -positionPoint.x;
  19615. position.y = positionPoint.y;
  19616. position.z = 0;
  19617. Vector3.scale(position, this.radius, position);
  19618. if (this.randomDirection) {
  19619. if (rand) {
  19620. rand.seed = randomSeeds[17];
  19621. ShapeUtils._randomPointUnitSphere(direction, rand);
  19622. randomSeeds[17] = rand.seed;
  19623. }
  19624. else {
  19625. ShapeUtils._randomPointUnitSphere(direction);
  19626. }
  19627. }
  19628. else {
  19629. position.cloneTo(direction);
  19630. }
  19631. }
  19632. cloneTo(destObject) {
  19633. super.cloneTo(destObject);
  19634. var destShape = destObject;
  19635. destShape.radius = this.radius;
  19636. destShape.arc = this.arc;
  19637. destShape.emitFromEdge = this.emitFromEdge;
  19638. destShape.randomDirection = this.randomDirection;
  19639. }
  19640. clone() {
  19641. var destShape = new CircleShape();
  19642. this.cloneTo(destShape);
  19643. return destShape;
  19644. }
  19645. }
  19646. CircleShape._tempPositionPoint = new Vector2();
  19647. class ConeShape extends BaseShape {
  19648. constructor() {
  19649. super();
  19650. this.angle = 25.0 / 180.0 * Math.PI;
  19651. this.radius = 1.0;
  19652. this.length = 5.0;
  19653. this.emitType = 0;
  19654. this.randomDirection = false;
  19655. }
  19656. _getShapeBoundBox(boundBox) {
  19657. const coneRadius2 = this.radius + this.length * Math.sin(this.angle);
  19658. const coneLength = this.length * Math.cos(this.angle);
  19659. var min = boundBox.min;
  19660. min.x = min.y = -coneRadius2;
  19661. min.z = 0;
  19662. var max = boundBox.max;
  19663. max.x = max.y = coneRadius2;
  19664. max.z = coneLength;
  19665. }
  19666. _getSpeedBoundBox(boundBox) {
  19667. const sinA = Math.sin(this.angle);
  19668. var min = boundBox.min;
  19669. min.x = min.y = -sinA;
  19670. min.z = 0;
  19671. var max = boundBox.max;
  19672. max.x = max.y = sinA;
  19673. max.z = 1;
  19674. }
  19675. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  19676. var positionPointE = ConeShape._tempPositionPoint;
  19677. var positionX;
  19678. var positionY;
  19679. var directionPointE;
  19680. var dirCosA = Math.cos(this.angle);
  19681. var dirSinA = Math.sin(this.angle);
  19682. switch (this.emitType) {
  19683. case 0:
  19684. if (rand) {
  19685. rand.seed = randomSeeds[16];
  19686. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint, rand);
  19687. randomSeeds[16] = rand.seed;
  19688. }
  19689. else {
  19690. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint);
  19691. }
  19692. positionX = positionPointE.x;
  19693. positionY = positionPointE.y;
  19694. position.x = positionX * this.radius;
  19695. position.y = positionY * this.radius;
  19696. position.z = 0;
  19697. if (this.randomDirection) {
  19698. if (rand) {
  19699. rand.seed = randomSeeds[17];
  19700. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint, rand);
  19701. randomSeeds[17] = rand.seed;
  19702. }
  19703. else {
  19704. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint);
  19705. }
  19706. directionPointE = ConeShape._tempDirectionPoint;
  19707. direction.x = directionPointE.x * dirSinA;
  19708. direction.y = directionPointE.y * dirSinA;
  19709. }
  19710. else {
  19711. direction.x = positionX * dirSinA;
  19712. direction.y = positionY * dirSinA;
  19713. }
  19714. direction.z = dirCosA;
  19715. break;
  19716. case 1:
  19717. if (rand) {
  19718. rand.seed = randomSeeds[16];
  19719. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint, rand);
  19720. randomSeeds[16] = rand.seed;
  19721. }
  19722. else {
  19723. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint);
  19724. }
  19725. positionX = positionPointE.x;
  19726. positionY = positionPointE.y;
  19727. position.x = positionX * this.radius;
  19728. position.y = positionY * this.radius;
  19729. position.z = 0;
  19730. if (this.randomDirection) {
  19731. if (rand) {
  19732. rand.seed = randomSeeds[17];
  19733. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint, rand);
  19734. randomSeeds[17] = rand.seed;
  19735. }
  19736. else {
  19737. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint);
  19738. }
  19739. directionPointE = ConeShape._tempDirectionPoint;
  19740. direction.x = directionPointE.x * dirSinA;
  19741. direction.y = directionPointE.y * dirSinA;
  19742. }
  19743. else {
  19744. direction.x = positionX * dirSinA;
  19745. direction.y = positionY * dirSinA;
  19746. }
  19747. direction.z = dirCosA;
  19748. break;
  19749. case 2:
  19750. if (rand) {
  19751. rand.seed = randomSeeds[16];
  19752. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint, rand);
  19753. }
  19754. else {
  19755. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint);
  19756. }
  19757. positionX = positionPointE.x;
  19758. positionY = positionPointE.y;
  19759. position.x = positionX * this.radius;
  19760. position.y = positionY * this.radius;
  19761. position.z = 0;
  19762. direction.x = positionX * dirSinA;
  19763. direction.y = positionY * dirSinA;
  19764. direction.z = dirCosA;
  19765. Vector3.normalize(direction, direction);
  19766. if (rand) {
  19767. Vector3.scale(direction, this.length * rand.getFloat(), direction);
  19768. randomSeeds[16] = rand.seed;
  19769. }
  19770. else {
  19771. Vector3.scale(direction, this.length * Math.random(), direction);
  19772. }
  19773. Vector3.add(position, direction, position);
  19774. if (this.randomDirection) {
  19775. if (rand) {
  19776. rand.seed = randomSeeds[17];
  19777. ShapeUtils._randomPointUnitSphere(direction, rand);
  19778. randomSeeds[17] = rand.seed;
  19779. }
  19780. else {
  19781. ShapeUtils._randomPointUnitSphere(direction);
  19782. }
  19783. }
  19784. break;
  19785. case 3:
  19786. if (rand) {
  19787. rand.seed = randomSeeds[16];
  19788. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint, rand);
  19789. }
  19790. else {
  19791. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint);
  19792. }
  19793. positionX = positionPointE.x;
  19794. positionY = positionPointE.y;
  19795. position.x = positionX * this.radius;
  19796. position.y = positionY * this.radius;
  19797. position.z = 0;
  19798. direction.x = positionX * dirSinA;
  19799. direction.y = positionY * dirSinA;
  19800. direction.z = dirCosA;
  19801. Vector3.normalize(direction, direction);
  19802. if (rand) {
  19803. Vector3.scale(direction, this.length * rand.getFloat(), direction);
  19804. randomSeeds[16] = rand.seed;
  19805. }
  19806. else {
  19807. Vector3.scale(direction, this.length * Math.random(), direction);
  19808. }
  19809. Vector3.add(position, direction, position);
  19810. if (this.randomDirection) {
  19811. if (rand) {
  19812. rand.seed = randomSeeds[17];
  19813. ShapeUtils._randomPointUnitSphere(direction, rand);
  19814. randomSeeds[17] = rand.seed;
  19815. }
  19816. else {
  19817. ShapeUtils._randomPointUnitSphere(direction);
  19818. }
  19819. }
  19820. break;
  19821. default:
  19822. throw new Error("ConeShape:emitType is invalid.");
  19823. }
  19824. }
  19825. cloneTo(destObject) {
  19826. super.cloneTo(destObject);
  19827. var destShape = destObject;
  19828. destShape.angle = this.angle;
  19829. destShape.radius = this.radius;
  19830. destShape.length = this.length;
  19831. destShape.emitType = this.emitType;
  19832. destShape.randomDirection = this.randomDirection;
  19833. }
  19834. clone() {
  19835. var destShape = new ConeShape();
  19836. this.cloneTo(destShape);
  19837. return destShape;
  19838. }
  19839. }
  19840. ConeShape._tempPositionPoint = new Vector2();
  19841. ConeShape._tempDirectionPoint = new Vector2();
  19842. class HemisphereShape extends BaseShape {
  19843. constructor() {
  19844. super();
  19845. this.radius = 1.0;
  19846. this.emitFromShell = false;
  19847. this.randomDirection = false;
  19848. }
  19849. _getShapeBoundBox(boundBox) {
  19850. var min = boundBox.min;
  19851. min.x = min.y = min.z = -this.radius;
  19852. var max = boundBox.max;
  19853. max.x = max.y = this.radius;
  19854. max.z = 0;
  19855. }
  19856. _getSpeedBoundBox(boundBox) {
  19857. var min = boundBox.min;
  19858. min.x = min.y = -1;
  19859. min.z = 0;
  19860. var max = boundBox.max;
  19861. max.x = max.y = max.z = 1;
  19862. }
  19863. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  19864. if (rand) {
  19865. rand.seed = randomSeeds[16];
  19866. if (this.emitFromShell)
  19867. ShapeUtils._randomPointUnitSphere(position, rand);
  19868. else
  19869. ShapeUtils._randomPointInsideUnitSphere(position, rand);
  19870. randomSeeds[16] = rand.seed;
  19871. }
  19872. else {
  19873. if (this.emitFromShell)
  19874. ShapeUtils._randomPointUnitSphere(position);
  19875. else
  19876. ShapeUtils._randomPointInsideUnitSphere(position);
  19877. }
  19878. Vector3.scale(position, this.radius, position);
  19879. var z = position.z;
  19880. (z < 0.0) && (position.z = z * -1.0);
  19881. if (this.randomDirection) {
  19882. if (rand) {
  19883. rand.seed = randomSeeds[17];
  19884. ShapeUtils._randomPointUnitSphere(direction, rand);
  19885. randomSeeds[17] = rand.seed;
  19886. }
  19887. else {
  19888. ShapeUtils._randomPointUnitSphere(direction);
  19889. }
  19890. }
  19891. else {
  19892. position.cloneTo(direction);
  19893. }
  19894. }
  19895. cloneTo(destObject) {
  19896. super.cloneTo(destObject);
  19897. var destShape = destObject;
  19898. destShape.radius = this.radius;
  19899. destShape.emitFromShell = this.emitFromShell;
  19900. destShape.randomDirection = this.randomDirection;
  19901. }
  19902. clone() {
  19903. var destShape = new HemisphereShape();
  19904. this.cloneTo(destShape);
  19905. return destShape;
  19906. }
  19907. }
  19908. class SphereShape extends BaseShape {
  19909. constructor() {
  19910. super();
  19911. this.radius = 1.0;
  19912. this.emitFromShell = false;
  19913. this.randomDirection = false;
  19914. }
  19915. _getShapeBoundBox(boundBox) {
  19916. var min = boundBox.min;
  19917. min.x = min.y = min.z = -this.radius;
  19918. var max = boundBox.max;
  19919. max.x = max.y = max.z = this.radius;
  19920. }
  19921. _getSpeedBoundBox(boundBox) {
  19922. var min = boundBox.min;
  19923. min.x = min.y = min.z = -1;
  19924. var max = boundBox.max;
  19925. max.x = max.y = max.z = 1;
  19926. }
  19927. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  19928. if (rand) {
  19929. rand.seed = randomSeeds[16];
  19930. if (this.emitFromShell)
  19931. ShapeUtils._randomPointUnitSphere(position, rand);
  19932. else
  19933. ShapeUtils._randomPointInsideUnitSphere(position, rand);
  19934. randomSeeds[16] = rand.seed;
  19935. }
  19936. else {
  19937. if (this.emitFromShell)
  19938. ShapeUtils._randomPointUnitSphere(position);
  19939. else
  19940. ShapeUtils._randomPointInsideUnitSphere(position);
  19941. }
  19942. Vector3.scale(position, this.radius, position);
  19943. if (this.randomDirection) {
  19944. if (rand) {
  19945. rand.seed = randomSeeds[17];
  19946. ShapeUtils._randomPointUnitSphere(direction, rand);
  19947. randomSeeds[17] = rand.seed;
  19948. }
  19949. else {
  19950. ShapeUtils._randomPointUnitSphere(direction);
  19951. }
  19952. }
  19953. else {
  19954. position.cloneTo(direction);
  19955. }
  19956. }
  19957. cloneTo(destObject) {
  19958. super.cloneTo(destObject);
  19959. var destShape = destObject;
  19960. destShape.radius = this.radius;
  19961. destShape.emitFromShell = this.emitFromShell;
  19962. destShape.randomDirection = this.randomDirection;
  19963. }
  19964. clone() {
  19965. var destShape = new SphereShape();
  19966. this.cloneTo(destShape);
  19967. return destShape;
  19968. }
  19969. }
  19970. class SizeOverLifetime {
  19971. get size() {
  19972. return this._size;
  19973. }
  19974. constructor(size) {
  19975. this._size = size;
  19976. }
  19977. cloneTo(destObject) {
  19978. var destSizeOverLifetime = destObject;
  19979. this._size.cloneTo(destSizeOverLifetime._size);
  19980. destSizeOverLifetime.enbale = this.enbale;
  19981. }
  19982. clone() {
  19983. var destSize;
  19984. switch (this._size.type) {
  19985. case 0:
  19986. if (this._size.separateAxes)
  19987. destSize = GradientSize.createByGradientSeparate(this._size.gradientX.clone(), this._size.gradientY.clone(), this._size.gradientZ.clone());
  19988. else
  19989. destSize = GradientSize.createByGradient(this._size.gradient.clone());
  19990. break;
  19991. case 1:
  19992. if (this._size.separateAxes)
  19993. destSize = GradientSize.createByRandomTwoConstantSeparate(this._size.constantMinSeparate.clone(), this._size.constantMaxSeparate.clone());
  19994. else
  19995. destSize = GradientSize.createByRandomTwoConstant(this._size.constantMin, this._size.constantMax);
  19996. break;
  19997. case 2:
  19998. if (this._size.separateAxes)
  19999. 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());
  20000. else
  20001. destSize = GradientSize.createByRandomTwoGradient(this._size.gradientMin.clone(), this._size.gradientMax.clone());
  20002. break;
  20003. }
  20004. var destSizeOverLifetime = new SizeOverLifetime(destSize);
  20005. destSizeOverLifetime.enbale = this.enbale;
  20006. return destSizeOverLifetime;
  20007. }
  20008. }
  20009. class StartFrame {
  20010. constructor() {
  20011. this._type = 0;
  20012. this._constant = 0;
  20013. this._constantMin = 0;
  20014. this._constantMax = 0;
  20015. }
  20016. static createByConstant(constant) {
  20017. var rotationOverLifetime = new StartFrame();
  20018. rotationOverLifetime._type = 0;
  20019. rotationOverLifetime._constant = constant;
  20020. return rotationOverLifetime;
  20021. }
  20022. static createByRandomTwoConstant(constantMin, constantMax) {
  20023. var rotationOverLifetime = new StartFrame();
  20024. rotationOverLifetime._type = 1;
  20025. rotationOverLifetime._constantMin = constantMin;
  20026. rotationOverLifetime._constantMax = constantMax;
  20027. return rotationOverLifetime;
  20028. }
  20029. get type() {
  20030. return this._type;
  20031. }
  20032. get constant() {
  20033. return this._constant;
  20034. }
  20035. get constantMin() {
  20036. return this._constantMin;
  20037. }
  20038. get constantMax() {
  20039. return this._constantMax;
  20040. }
  20041. cloneTo(destObject) {
  20042. var destStartFrame = destObject;
  20043. destStartFrame._type = this._type;
  20044. destStartFrame._constant = this._constant;
  20045. destStartFrame._constantMin = this._constantMin;
  20046. destStartFrame._constantMax = this._constantMax;
  20047. }
  20048. clone() {
  20049. var destStartFrame = new StartFrame();
  20050. this.cloneTo(destStartFrame);
  20051. return destStartFrame;
  20052. }
  20053. }
  20054. class TextureSheetAnimation {
  20055. constructor(frame, startFrame) {
  20056. this.type = 0;
  20057. this.randomRow = false;
  20058. this.rowIndex = 0;
  20059. this.cycles = 0;
  20060. this.enableUVChannels = 0;
  20061. this.enable = false;
  20062. this.tiles = new Vector2(1, 1);
  20063. this.type = 0;
  20064. this.randomRow = true;
  20065. this.rowIndex = 0;
  20066. this.cycles = 1;
  20067. this.enableUVChannels = 1;
  20068. this._frame = frame;
  20069. this._startFrame = startFrame;
  20070. }
  20071. get frame() {
  20072. return this._frame;
  20073. }
  20074. get startFrame() {
  20075. return this._startFrame;
  20076. }
  20077. cloneTo(destObject) {
  20078. var destTextureSheetAnimation = destObject;
  20079. this.tiles.cloneTo(destTextureSheetAnimation.tiles);
  20080. destTextureSheetAnimation.type = this.type;
  20081. destTextureSheetAnimation.randomRow = this.randomRow;
  20082. destTextureSheetAnimation.rowIndex = this.rowIndex;
  20083. destTextureSheetAnimation.cycles = this.cycles;
  20084. destTextureSheetAnimation.enableUVChannels = this.enableUVChannels;
  20085. destTextureSheetAnimation.enable = this.enable;
  20086. this._frame.cloneTo(destTextureSheetAnimation._frame);
  20087. this._startFrame.cloneTo(destTextureSheetAnimation._startFrame);
  20088. }
  20089. clone() {
  20090. var destFrame;
  20091. switch (this._frame.type) {
  20092. case 0:
  20093. destFrame = FrameOverTime.createByConstant(this._frame.constant);
  20094. break;
  20095. case 1:
  20096. destFrame = FrameOverTime.createByOverTime(this._frame.frameOverTimeData.clone());
  20097. break;
  20098. case 2:
  20099. destFrame = FrameOverTime.createByRandomTwoConstant(this._frame.constantMin, this._frame.constantMax);
  20100. break;
  20101. case 3:
  20102. destFrame = FrameOverTime.createByRandomTwoOverTime(this._frame.frameOverTimeDataMin.clone(), this._frame.frameOverTimeDataMax.clone());
  20103. break;
  20104. }
  20105. var destStartFrame;
  20106. switch (this._startFrame.type) {
  20107. case 0:
  20108. destStartFrame = StartFrame.createByConstant(this._startFrame.constant);
  20109. break;
  20110. case 1:
  20111. destStartFrame = StartFrame.createByRandomTwoConstant(this._startFrame.constantMin, this._startFrame.constantMax);
  20112. break;
  20113. }
  20114. var destTextureSheetAnimation = new TextureSheetAnimation(destFrame, destStartFrame);
  20115. this.cloneTo(destTextureSheetAnimation);
  20116. return destTextureSheetAnimation;
  20117. }
  20118. }
  20119. class VelocityOverLifetime {
  20120. constructor(velocity) {
  20121. this.enbale = false;
  20122. this.space = 0;
  20123. this._velocity = velocity;
  20124. }
  20125. get velocity() {
  20126. return this._velocity;
  20127. }
  20128. cloneTo(destObject) {
  20129. var destVelocityOverLifetime = destObject;
  20130. this._velocity.cloneTo(destVelocityOverLifetime._velocity);
  20131. destVelocityOverLifetime.enbale = this.enbale;
  20132. destVelocityOverLifetime.space = this.space;
  20133. }
  20134. clone() {
  20135. var destVelocity;
  20136. switch (this._velocity.type) {
  20137. case 0:
  20138. destVelocity = GradientVelocity.createByConstant(this._velocity.constant.clone());
  20139. break;
  20140. case 1:
  20141. destVelocity = GradientVelocity.createByGradient(this._velocity.gradientX.clone(), this._velocity.gradientY.clone(), this._velocity.gradientZ.clone());
  20142. break;
  20143. case 2:
  20144. destVelocity = GradientVelocity.createByRandomTwoConstant(this._velocity.constantMin.clone(), this._velocity.constantMax.clone());
  20145. break;
  20146. case 3:
  20147. destVelocity = GradientVelocity.createByRandomTwoGradient(this._velocity.gradientXMin.clone(), this._velocity.gradientYMin.clone(), this._velocity.gradientZMin.clone(), this._velocity.gradientXMax.clone(), this._velocity.gradientYMax.clone(), this._velocity.gradientZMax.clone());
  20148. break;
  20149. }
  20150. var destVelocityOverLifetime = new VelocityOverLifetime(destVelocity);
  20151. destVelocityOverLifetime.enbale = this.enbale;
  20152. destVelocityOverLifetime.space = this.space;
  20153. return destVelocityOverLifetime;
  20154. }
  20155. }
  20156. class ShuriKenParticle3D extends RenderableSprite3D {
  20157. static __init__() {
  20158. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD = Shader3D.getDefineByName("SPHERHBILLBOARD");
  20159. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD = Shader3D.getDefineByName("STRETCHEDBILLBOARD");
  20160. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD = Shader3D.getDefineByName("HORIZONTALBILLBOARD");
  20161. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD = Shader3D.getDefineByName("VERTICALBILLBOARD");
  20162. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME = Shader3D.getDefineByName("COLOROVERLIFETIME");
  20163. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME = Shader3D.getDefineByName("RANDOMCOLOROVERLIFETIME");
  20164. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT = Shader3D.getDefineByName("VELOCITYOVERLIFETIMECONSTANT");
  20165. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE = Shader3D.getDefineByName("VELOCITYOVERLIFETIMECURVE");
  20166. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT = Shader3D.getDefineByName("VELOCITYOVERLIFETIMERANDOMCONSTANT");
  20167. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE = Shader3D.getDefineByName("VELOCITYOVERLIFETIMERANDOMCURVE");
  20168. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE = Shader3D.getDefineByName("TEXTURESHEETANIMATIONCURVE");
  20169. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE = Shader3D.getDefineByName("TEXTURESHEETANIMATIONRANDOMCURVE");
  20170. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME = Shader3D.getDefineByName("ROTATIONOVERLIFETIME");
  20171. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE = Shader3D.getDefineByName("ROTATIONOVERLIFETIMESEPERATE");
  20172. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT = Shader3D.getDefineByName("ROTATIONOVERLIFETIMECONSTANT");
  20173. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE = Shader3D.getDefineByName("ROTATIONOVERLIFETIMECURVE");
  20174. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS = Shader3D.getDefineByName("ROTATIONOVERLIFETIMERANDOMCONSTANTS");
  20175. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES = Shader3D.getDefineByName("ROTATIONOVERLIFETIMERANDOMCURVES");
  20176. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE = Shader3D.getDefineByName("SIZEOVERLIFETIMECURVE");
  20177. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE = Shader3D.getDefineByName("SIZEOVERLIFETIMECURVESEPERATE");
  20178. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES = Shader3D.getDefineByName("SIZEOVERLIFETIMERANDOMCURVES");
  20179. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE = Shader3D.getDefineByName("SIZEOVERLIFETIMERANDOMCURVESSEPERATE");
  20180. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH = Shader3D.getDefineByName("RENDERMODE_MESH");
  20181. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE = Shader3D.getDefineByName("SHAPE");
  20182. }
  20183. get particleSystem() {
  20184. return this._particleSystem;
  20185. }
  20186. get particleRenderer() {
  20187. return this._render;
  20188. }
  20189. constructor() {
  20190. super(null);
  20191. this._render = new ShurikenParticleRenderer(this);
  20192. this._particleSystem = new ShurikenParticleSystem(this);
  20193. var elements = this._render._renderElements;
  20194. var element = elements[0] = new RenderElement();
  20195. element.setTransform(this._transform);
  20196. element.render = this._render;
  20197. element.setGeometry(this._particleSystem);
  20198. element.material = ShurikenParticleMaterial.defaultMaterial;
  20199. }
  20200. static _initStartLife(gradientData) {
  20201. var gradient = new GradientDataNumber();
  20202. var startLifetimesData = gradientData.startLifetimes;
  20203. for (var i = 0, n = startLifetimesData.length; i < n; i++) {
  20204. var valueData = startLifetimesData[i];
  20205. gradient.add(valueData.key, valueData.value);
  20206. }
  20207. return gradient;
  20208. }
  20209. _initParticleVelocity(gradientData) {
  20210. var gradient = new GradientDataNumber();
  20211. var velocitysData = gradientData.velocitys;
  20212. for (var i = 0, n = velocitysData.length; i < n; i++) {
  20213. var valueData = velocitysData[i];
  20214. gradient.add(valueData.key, valueData.value);
  20215. }
  20216. return gradient;
  20217. }
  20218. _initParticleColor(gradientColorData) {
  20219. var gradientColor = new Gradient(4, 4);
  20220. var alphasData = gradientColorData.alphas;
  20221. var i, n;
  20222. for (i = 0, n = alphasData.length; i < n; i++) {
  20223. var alphaData = alphasData[i];
  20224. if ((i === 3) && ((alphaData.key !== 1))) {
  20225. alphaData.key = 1;
  20226. console.log("GradientDataColor warning:the forth key is be force set to 1.");
  20227. }
  20228. gradientColor.addColorAlpha(alphaData.key, alphaData.value);
  20229. }
  20230. var rgbsData = gradientColorData.rgbs;
  20231. for (i = 0, n = rgbsData.length; i < n; i++) {
  20232. var rgbData = rgbsData[i];
  20233. var rgbValue = rgbData.value;
  20234. if ((i === 3) && ((rgbData.key !== 1))) {
  20235. rgbData.key = 1;
  20236. console.log("GradientDataColor warning:the forth key is be force set to 1.");
  20237. }
  20238. gradientColor.addColorRGB(rgbData.key, new Color(rgbValue[0], rgbValue[1], rgbValue[2], 1.0));
  20239. }
  20240. return gradientColor;
  20241. }
  20242. _initParticleSize(gradientSizeData) {
  20243. var gradientSize = new GradientDataNumber();
  20244. var sizesData = gradientSizeData.sizes;
  20245. for (var i = 0, n = sizesData.length; i < n; i++) {
  20246. var valueData = sizesData[i];
  20247. gradientSize.add(valueData.key, valueData.value);
  20248. }
  20249. return gradientSize;
  20250. }
  20251. _initParticleRotation(gradientData) {
  20252. var gradient = new GradientDataNumber();
  20253. var angularVelocitysData = gradientData.angularVelocitys;
  20254. for (var i = 0, n = angularVelocitysData.length; i < n; i++) {
  20255. var valueData = angularVelocitysData[i];
  20256. gradient.add(valueData.key, valueData.value / 180.0 * Math.PI);
  20257. }
  20258. return gradient;
  20259. }
  20260. _initParticleFrame(overTimeFramesData) {
  20261. var overTimeFrame = new GradientDataInt();
  20262. var framesData = overTimeFramesData.frames;
  20263. for (var i = 0, n = framesData.length; i < n; i++) {
  20264. var frameData = framesData[i];
  20265. overTimeFrame.add(frameData.key, frameData.value);
  20266. }
  20267. return overTimeFrame;
  20268. }
  20269. _parse(data, spriteMap) {
  20270. super._parse(data, spriteMap);
  20271. const anglelToRad = Math.PI / 180.0;
  20272. var i, n;
  20273. var particleRender = this.particleRenderer;
  20274. var material;
  20275. var materialData = data.material;
  20276. (materialData) && (material = Laya.Loader.getRes(materialData.path));
  20277. particleRender.sharedMaterial = material;
  20278. var meshPath = data.meshPath;
  20279. (meshPath) && (particleRender.mesh = Laya.Loader.getRes(meshPath));
  20280. particleRender.renderMode = data.renderMode;
  20281. particleRender.stretchedBillboardCameraSpeedScale = data.stretchedBillboardCameraSpeedScale;
  20282. particleRender.stretchedBillboardSpeedScale = data.stretchedBillboardSpeedScale;
  20283. particleRender.stretchedBillboardLengthScale = data.stretchedBillboardLengthScale;
  20284. particleRender.sortingFudge = data.sortingFudge ? data.sortingFudge : 0.0;
  20285. var particleSystem = this.particleSystem;
  20286. particleSystem.isPerformanceMode = data.isPerformanceMode;
  20287. particleSystem.duration = data.duration;
  20288. particleSystem.looping = data.looping;
  20289. particleSystem.prewarm = data.prewarm;
  20290. particleSystem.startDelayType = data.startDelayType;
  20291. particleSystem.startDelay = data.startDelay;
  20292. particleSystem.startDelayMin = data.startDelayMin;
  20293. particleSystem.startDelayMax = data.startDelayMax;
  20294. particleSystem.startLifetimeType = data.startLifetimeType;
  20295. particleSystem.startLifetimeConstant = data.startLifetimeConstant;
  20296. particleSystem.startLifeTimeGradient = ShuriKenParticle3D._initStartLife(data.startLifetimeGradient);
  20297. particleSystem.startLifetimeConstantMin = data.startLifetimeConstantMin;
  20298. particleSystem.startLifetimeConstantMax = data.startLifetimeConstantMax;
  20299. particleSystem.startLifeTimeGradientMin = ShuriKenParticle3D._initStartLife(data.startLifetimeGradientMin);
  20300. particleSystem.startLifeTimeGradientMax = ShuriKenParticle3D._initStartLife(data.startLifetimeGradientMax);
  20301. particleSystem.startSpeedType = data.startSpeedType;
  20302. particleSystem.startSpeedConstant = data.startSpeedConstant;
  20303. particleSystem.startSpeedConstantMin = data.startSpeedConstantMin;
  20304. particleSystem.startSpeedConstantMax = data.startSpeedConstantMax;
  20305. particleSystem.threeDStartSize = data.threeDStartSize;
  20306. particleSystem.startSizeType = data.startSizeType;
  20307. particleSystem.startSizeConstant = data.startSizeConstant;
  20308. var startSizeConstantSeparateArray = data.startSizeConstantSeparate;
  20309. var startSizeConstantSeparateElement = particleSystem.startSizeConstantSeparate;
  20310. startSizeConstantSeparateElement.x = startSizeConstantSeparateArray[0];
  20311. startSizeConstantSeparateElement.y = startSizeConstantSeparateArray[1];
  20312. startSizeConstantSeparateElement.z = startSizeConstantSeparateArray[2];
  20313. particleSystem.startSizeConstantMin = data.startSizeConstantMin;
  20314. particleSystem.startSizeConstantMax = data.startSizeConstantMax;
  20315. var startSizeConstantMinSeparateArray = data.startSizeConstantMinSeparate;
  20316. var startSizeConstantMinSeparateElement = particleSystem.startSizeConstantMinSeparate;
  20317. startSizeConstantMinSeparateElement.x = startSizeConstantMinSeparateArray[0];
  20318. startSizeConstantMinSeparateElement.y = startSizeConstantMinSeparateArray[1];
  20319. startSizeConstantMinSeparateElement.z = startSizeConstantMinSeparateArray[2];
  20320. var startSizeConstantMaxSeparateArray = data.startSizeConstantMaxSeparate;
  20321. var startSizeConstantMaxSeparateElement = particleSystem.startSizeConstantMaxSeparate;
  20322. startSizeConstantMaxSeparateElement.x = startSizeConstantMaxSeparateArray[0];
  20323. startSizeConstantMaxSeparateElement.y = startSizeConstantMaxSeparateArray[1];
  20324. startSizeConstantMaxSeparateElement.z = startSizeConstantMaxSeparateArray[2];
  20325. particleSystem.threeDStartRotation = data.threeDStartRotation;
  20326. particleSystem.startRotationType = data.startRotationType;
  20327. particleSystem.startRotationConstant = data.startRotationConstant * anglelToRad;
  20328. var startRotationConstantSeparateArray = data.startRotationConstantSeparate;
  20329. var startRotationConstantSeparateElement = particleSystem.startRotationConstantSeparate;
  20330. startRotationConstantSeparateElement.x = startRotationConstantSeparateArray[0] * anglelToRad;
  20331. startRotationConstantSeparateElement.y = startRotationConstantSeparateArray[1] * anglelToRad;
  20332. startRotationConstantSeparateElement.z = startRotationConstantSeparateArray[2] * anglelToRad;
  20333. particleSystem.startRotationConstantMin = data.startRotationConstantMin * anglelToRad;
  20334. particleSystem.startRotationConstantMax = data.startRotationConstantMax * anglelToRad;
  20335. var startRotationConstantMinSeparateArray = data.startRotationConstantMinSeparate;
  20336. var startRotationConstantMinSeparateElement = particleSystem.startRotationConstantMinSeparate;
  20337. startRotationConstantMinSeparateElement.x = startRotationConstantMinSeparateArray[0] * anglelToRad;
  20338. startRotationConstantMinSeparateElement.y = startRotationConstantMinSeparateArray[1] * anglelToRad;
  20339. startRotationConstantMinSeparateElement.z = startRotationConstantMinSeparateArray[2] * anglelToRad;
  20340. var startRotationConstantMaxSeparateArray = data.startRotationConstantMaxSeparate;
  20341. var startRotationConstantMaxSeparateElement = particleSystem.startRotationConstantMaxSeparate;
  20342. startRotationConstantMaxSeparateElement.x = startRotationConstantMaxSeparateArray[0] * anglelToRad;
  20343. startRotationConstantMaxSeparateElement.y = startRotationConstantMaxSeparateArray[1] * anglelToRad;
  20344. startRotationConstantMaxSeparateElement.z = startRotationConstantMaxSeparateArray[2] * anglelToRad;
  20345. particleSystem.randomizeRotationDirection = data.randomizeRotationDirection;
  20346. particleSystem.startColorType = data.startColorType;
  20347. var startColorConstantArray = data.startColorConstant;
  20348. var startColorConstantElement = particleSystem.startColorConstant;
  20349. startColorConstantElement.x = startColorConstantArray[0];
  20350. startColorConstantElement.y = startColorConstantArray[1];
  20351. startColorConstantElement.z = startColorConstantArray[2];
  20352. startColorConstantElement.w = startColorConstantArray[3];
  20353. var startColorConstantMinArray = data.startColorConstantMin;
  20354. var startColorConstantMinElement = particleSystem.startColorConstantMin;
  20355. startColorConstantMinElement.x = startColorConstantMinArray[0];
  20356. startColorConstantMinElement.y = startColorConstantMinArray[1];
  20357. startColorConstantMinElement.z = startColorConstantMinArray[2];
  20358. startColorConstantMinElement.w = startColorConstantMinArray[3];
  20359. var startColorConstantMaxArray = data.startColorConstantMax;
  20360. var startColorConstantMaxElement = particleSystem.startColorConstantMax;
  20361. startColorConstantMaxElement.x = startColorConstantMaxArray[0];
  20362. startColorConstantMaxElement.y = startColorConstantMaxArray[1];
  20363. startColorConstantMaxElement.z = startColorConstantMaxArray[2];
  20364. startColorConstantMaxElement.w = startColorConstantMaxArray[3];
  20365. particleSystem.gravityModifier = data.gravityModifier;
  20366. particleSystem.simulationSpace = data.simulationSpace;
  20367. (data.simulationSpeed !== undefined) && (particleSystem.simulationSpeed = data.simulationSpeed);
  20368. particleSystem.scaleMode = data.scaleMode;
  20369. particleSystem.playOnAwake = data.playOnAwake;
  20370. particleSystem.maxParticles = data.maxParticles;
  20371. var autoRandomSeed = data.autoRandomSeed;
  20372. (autoRandomSeed != null) && (particleSystem.autoRandomSeed = autoRandomSeed);
  20373. var randomSeed = data.randomSeed;
  20374. (randomSeed != null) && (particleSystem.randomSeed[0] = randomSeed);
  20375. var emissionData = data.emission;
  20376. var emission = particleSystem.emission;
  20377. if (emissionData) {
  20378. emission.emissionRate = emissionData.emissionRate;
  20379. var burstsData = emissionData.bursts;
  20380. if (burstsData)
  20381. for (i = 0, n = burstsData.length; i < n; i++) {
  20382. var brust = burstsData[i];
  20383. emission.addBurst(new Burst(brust.time, brust.min, brust.max));
  20384. }
  20385. emission.enbale = emissionData.enable;
  20386. }
  20387. else {
  20388. emission.enbale = false;
  20389. }
  20390. var shapeData = data.shape;
  20391. if (shapeData) {
  20392. var shape;
  20393. switch (shapeData.shapeType) {
  20394. case 0:
  20395. var sphereShape;
  20396. shape = sphereShape = new SphereShape();
  20397. sphereShape.radius = shapeData.sphereRadius;
  20398. sphereShape.emitFromShell = shapeData.sphereEmitFromShell;
  20399. sphereShape.randomDirection = shapeData.sphereRandomDirection;
  20400. break;
  20401. case 1:
  20402. var hemiSphereShape;
  20403. shape = hemiSphereShape = new HemisphereShape();
  20404. hemiSphereShape.radius = shapeData.hemiSphereRadius;
  20405. hemiSphereShape.emitFromShell = shapeData.hemiSphereEmitFromShell;
  20406. hemiSphereShape.randomDirection = shapeData.hemiSphereRandomDirection;
  20407. break;
  20408. case 2:
  20409. var coneShape;
  20410. shape = coneShape = new ConeShape();
  20411. coneShape.angle = shapeData.coneAngle * anglelToRad;
  20412. coneShape.radius = shapeData.coneRadius;
  20413. coneShape.length = shapeData.coneLength;
  20414. coneShape.emitType = shapeData.coneEmitType;
  20415. coneShape.randomDirection = shapeData.coneRandomDirection;
  20416. break;
  20417. case 3:
  20418. var boxShape;
  20419. shape = boxShape = new BoxShape();
  20420. boxShape.x = shapeData.boxX;
  20421. boxShape.y = shapeData.boxY;
  20422. boxShape.z = shapeData.boxZ;
  20423. boxShape.randomDirection = shapeData.boxRandomDirection;
  20424. break;
  20425. case 7:
  20426. var circleShape;
  20427. shape = circleShape = new CircleShape();
  20428. circleShape.radius = shapeData.circleRadius;
  20429. circleShape.arc = shapeData.circleArc * anglelToRad;
  20430. circleShape.emitFromEdge = shapeData.circleEmitFromEdge;
  20431. circleShape.randomDirection = shapeData.circleRandomDirection;
  20432. break;
  20433. default:
  20434. var tempShape;
  20435. shape = tempShape = new CircleShape();
  20436. tempShape.radius = shapeData.circleRadius;
  20437. tempShape.arc = shapeData.circleArc * anglelToRad;
  20438. tempShape.emitFromEdge = shapeData.circleEmitFromEdge;
  20439. tempShape.randomDirection = shapeData.circleRandomDirection;
  20440. break;
  20441. }
  20442. shape.enable = shapeData.enable;
  20443. particleSystem.shape = shape;
  20444. }
  20445. var velocityOverLifetimeData = data.velocityOverLifetime;
  20446. if (velocityOverLifetimeData) {
  20447. var velocityData = velocityOverLifetimeData.velocity;
  20448. var velocity;
  20449. switch (velocityData.type) {
  20450. case 0:
  20451. var constantData = velocityData.constant;
  20452. velocity = GradientVelocity.createByConstant(new Vector3(constantData[0], constantData[1], constantData[2]));
  20453. break;
  20454. case 1:
  20455. velocity = GradientVelocity.createByGradient(this._initParticleVelocity(velocityData.gradientX), this._initParticleVelocity(velocityData.gradientY), this._initParticleVelocity(velocityData.gradientZ));
  20456. break;
  20457. case 2:
  20458. var constantMinData = velocityData.constantMin;
  20459. var constantMaxData = velocityData.constantMax;
  20460. velocity = GradientVelocity.createByRandomTwoConstant(new Vector3(constantMinData[0], constantMinData[1], constantMinData[2]), new Vector3(constantMaxData[0], constantMaxData[1], constantMaxData[2]));
  20461. break;
  20462. case 3:
  20463. 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));
  20464. break;
  20465. }
  20466. var velocityOverLifetime = new VelocityOverLifetime(velocity);
  20467. velocityOverLifetime.space = velocityOverLifetimeData.space;
  20468. velocityOverLifetime.enbale = velocityOverLifetimeData.enable;
  20469. particleSystem.velocityOverLifetime = velocityOverLifetime;
  20470. }
  20471. var colorOverLifetimeData = data.colorOverLifetime;
  20472. if (colorOverLifetimeData) {
  20473. var colorData = colorOverLifetimeData.color;
  20474. var color;
  20475. switch (colorData.type) {
  20476. case 0:
  20477. var constColorData = colorData.constant;
  20478. color = GradientColor.createByConstant(new Vector4(constColorData[0], constColorData[1], constColorData[2], constColorData[3]));
  20479. break;
  20480. case 1:
  20481. color = GradientColor.createByGradient(this._initParticleColor(colorData.gradient));
  20482. break;
  20483. case 2:
  20484. var minConstColorData = colorData.constantMin;
  20485. var maxConstColorData = colorData.constantMax;
  20486. color = GradientColor.createByRandomTwoConstant(new Vector4(minConstColorData[0], minConstColorData[1], minConstColorData[2], minConstColorData[3]), new Vector4(maxConstColorData[0], maxConstColorData[1], maxConstColorData[2], maxConstColorData[3]));
  20487. break;
  20488. case 3:
  20489. color = GradientColor.createByRandomTwoGradient(this._initParticleColor(colorData.gradientMin), this._initParticleColor(colorData.gradientMax));
  20490. break;
  20491. }
  20492. var colorOverLifetime = new ColorOverLifetime(color);
  20493. colorOverLifetime.enbale = colorOverLifetimeData.enable;
  20494. particleSystem.colorOverLifetime = colorOverLifetime;
  20495. }
  20496. var sizeOverLifetimeData = data.sizeOverLifetime;
  20497. if (sizeOverLifetimeData) {
  20498. var sizeData = sizeOverLifetimeData.size;
  20499. var size;
  20500. switch (sizeData.type) {
  20501. case 0:
  20502. if (sizeData.separateAxes) {
  20503. size = GradientSize.createByGradientSeparate(this._initParticleSize(sizeData.gradientX), this._initParticleSize(sizeData.gradientY), this._initParticleSize(sizeData.gradientZ));
  20504. }
  20505. else {
  20506. size = GradientSize.createByGradient(this._initParticleSize(sizeData.gradient));
  20507. }
  20508. break;
  20509. case 1:
  20510. if (sizeData.separateAxes) {
  20511. var constantMinSeparateData = sizeData.constantMinSeparate;
  20512. var constantMaxSeparateData = sizeData.constantMaxSeparate;
  20513. size = GradientSize.createByRandomTwoConstantSeparate(new Vector3(constantMinSeparateData[0], constantMinSeparateData[1], constantMinSeparateData[2]), new Vector3(constantMaxSeparateData[0], constantMaxSeparateData[1], constantMaxSeparateData[2]));
  20514. }
  20515. else {
  20516. size = GradientSize.createByRandomTwoConstant(sizeData.constantMin, sizeData.constantMax);
  20517. }
  20518. break;
  20519. case 2:
  20520. if (sizeData.separateAxes) {
  20521. 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));
  20522. }
  20523. else {
  20524. size = GradientSize.createByRandomTwoGradient(this._initParticleSize(sizeData.gradientMin), this._initParticleSize(sizeData.gradientMax));
  20525. }
  20526. break;
  20527. }
  20528. var sizeOverLifetime = new SizeOverLifetime(size);
  20529. sizeOverLifetime.enbale = sizeOverLifetimeData.enable;
  20530. particleSystem.sizeOverLifetime = sizeOverLifetime;
  20531. }
  20532. var rotationOverLifetimeData = data.rotationOverLifetime;
  20533. if (rotationOverLifetimeData) {
  20534. var angularVelocityData = rotationOverLifetimeData.angularVelocity;
  20535. var angularVelocity;
  20536. switch (angularVelocityData.type) {
  20537. case 0:
  20538. if (angularVelocityData.separateAxes) {
  20539. var conSep = angularVelocityData.constantSeparate;
  20540. angularVelocity = GradientAngularVelocity.createByConstantSeparate(new Vector3(conSep[0] * anglelToRad, conSep[1] * anglelToRad, conSep[2] * anglelToRad));
  20541. }
  20542. else {
  20543. angularVelocity = GradientAngularVelocity.createByConstant(angularVelocityData.constant * anglelToRad);
  20544. }
  20545. break;
  20546. case 1:
  20547. if (angularVelocityData.separateAxes) {
  20548. angularVelocity = GradientAngularVelocity.createByGradientSeparate(this._initParticleRotation(angularVelocityData.gradientX), this._initParticleRotation(angularVelocityData.gradientY), this._initParticleRotation(angularVelocityData.gradientZ));
  20549. }
  20550. else {
  20551. angularVelocity = GradientAngularVelocity.createByGradient(this._initParticleRotation(angularVelocityData.gradient));
  20552. }
  20553. break;
  20554. case 2:
  20555. if (angularVelocityData.separateAxes) {
  20556. var minSep = angularVelocityData.constantMinSeparate;
  20557. var maxSep = angularVelocityData.constantMaxSeparate;
  20558. 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));
  20559. }
  20560. else {
  20561. angularVelocity = GradientAngularVelocity.createByRandomTwoConstant(angularVelocityData.constantMin * anglelToRad, angularVelocityData.constantMax * anglelToRad);
  20562. }
  20563. break;
  20564. case 3:
  20565. if (angularVelocityData.separateAxes) ;
  20566. else {
  20567. angularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._initParticleRotation(angularVelocityData.gradientMin), this._initParticleRotation(angularVelocityData.gradientMax));
  20568. }
  20569. break;
  20570. }
  20571. var rotationOverLifetime = new RotationOverLifetime(angularVelocity);
  20572. rotationOverLifetime.enbale = rotationOverLifetimeData.enable;
  20573. particleSystem.rotationOverLifetime = rotationOverLifetime;
  20574. }
  20575. var textureSheetAnimationData = data.textureSheetAnimation;
  20576. if (textureSheetAnimationData) {
  20577. var frameData = textureSheetAnimationData.frame;
  20578. var frameOverTime;
  20579. switch (frameData.type) {
  20580. case 0:
  20581. frameOverTime = FrameOverTime.createByConstant(frameData.constant);
  20582. break;
  20583. case 1:
  20584. frameOverTime = FrameOverTime.createByOverTime(this._initParticleFrame(frameData.overTime));
  20585. break;
  20586. case 2:
  20587. frameOverTime = FrameOverTime.createByRandomTwoConstant(frameData.constantMin, frameData.constantMax);
  20588. break;
  20589. case 3:
  20590. frameOverTime = FrameOverTime.createByRandomTwoOverTime(this._initParticleFrame(frameData.overTimeMin), this._initParticleFrame(frameData.overTimeMax));
  20591. break;
  20592. }
  20593. var startFrameData = textureSheetAnimationData.startFrame;
  20594. var startFrame;
  20595. switch (startFrameData.type) {
  20596. case 0:
  20597. startFrame = StartFrame.createByConstant(startFrameData.constant);
  20598. break;
  20599. case 1:
  20600. startFrame = StartFrame.createByRandomTwoConstant(startFrameData.constantMin, startFrameData.constantMax);
  20601. break;
  20602. }
  20603. var textureSheetAnimation = new TextureSheetAnimation(frameOverTime, startFrame);
  20604. textureSheetAnimation.enable = textureSheetAnimationData.enable;
  20605. var tilesData = textureSheetAnimationData.tiles;
  20606. textureSheetAnimation.tiles = new Vector2(tilesData[0], tilesData[1]);
  20607. textureSheetAnimation.type = textureSheetAnimationData.type;
  20608. textureSheetAnimation.randomRow = textureSheetAnimationData.randomRow;
  20609. var rowIndex = textureSheetAnimationData.rowIndex;
  20610. (rowIndex !== undefined) && (textureSheetAnimation.rowIndex = rowIndex);
  20611. textureSheetAnimation.cycles = textureSheetAnimationData.cycles;
  20612. particleSystem.textureSheetAnimation = textureSheetAnimation;
  20613. }
  20614. }
  20615. _activeHierarchy(activeChangeComponents) {
  20616. super._activeHierarchy(activeChangeComponents);
  20617. (this.particleSystem.playOnAwake) && (this.particleSystem.play());
  20618. }
  20619. _inActiveHierarchy(activeChangeComponents) {
  20620. super._inActiveHierarchy(activeChangeComponents);
  20621. (this.particleSystem.isAlive) && (this.particleSystem.simulate(0, true));
  20622. }
  20623. _cloneTo(destObject, srcSprite, dstSprite) {
  20624. var destShuriKenParticle3D = destObject;
  20625. var destParticleSystem = destShuriKenParticle3D._particleSystem;
  20626. this._particleSystem.cloneTo(destParticleSystem);
  20627. var destParticleRender = destShuriKenParticle3D._render;
  20628. var particleRender = this._render;
  20629. destParticleRender.sharedMaterials = particleRender.sharedMaterials;
  20630. destParticleRender.enable = particleRender.enable;
  20631. destParticleRender.renderMode = particleRender.renderMode;
  20632. destParticleRender.mesh = particleRender.mesh;
  20633. destParticleRender.stretchedBillboardCameraSpeedScale = particleRender.stretchedBillboardCameraSpeedScale;
  20634. destParticleRender.stretchedBillboardSpeedScale = particleRender.stretchedBillboardSpeedScale;
  20635. destParticleRender.stretchedBillboardLengthScale = particleRender.stretchedBillboardLengthScale;
  20636. destParticleRender.sortingFudge = particleRender.sortingFudge;
  20637. super._cloneTo(destObject, srcSprite, dstSprite);
  20638. }
  20639. destroy(destroyChild = true) {
  20640. if (this.destroyed)
  20641. return;
  20642. super.destroy(destroyChild);
  20643. this._particleSystem.destroy();
  20644. this._particleSystem = null;
  20645. }
  20646. _create() {
  20647. return new ShuriKenParticle3D();
  20648. }
  20649. }
  20650. class PixelLineMaterial extends BaseMaterial {
  20651. constructor() {
  20652. super();
  20653. this.setShaderName("LineShader");
  20654. this._shaderValues.setVector(PixelLineMaterial.COLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  20655. }
  20656. static __initDefine__() {
  20657. }
  20658. get color() {
  20659. return this._shaderValues.getVector(PixelLineMaterial.COLOR);
  20660. }
  20661. set color(value) {
  20662. this._shaderValues.setVector(PixelLineMaterial.COLOR, value);
  20663. }
  20664. set depthWrite(value) {
  20665. this._shaderValues.setBool(PixelLineMaterial.DEPTH_WRITE, value);
  20666. }
  20667. get depthWrite() {
  20668. return this._shaderValues.getBool(PixelLineMaterial.DEPTH_WRITE);
  20669. }
  20670. set cull(value) {
  20671. this._shaderValues.setInt(PixelLineMaterial.CULL, value);
  20672. }
  20673. get cull() {
  20674. return this._shaderValues.getInt(PixelLineMaterial.CULL);
  20675. }
  20676. set blend(value) {
  20677. this._shaderValues.setInt(PixelLineMaterial.BLEND, value);
  20678. }
  20679. get blend() {
  20680. return this._shaderValues.getInt(PixelLineMaterial.BLEND);
  20681. }
  20682. set blendSrc(value) {
  20683. this._shaderValues.setInt(PixelLineMaterial.BLEND_SRC, value);
  20684. }
  20685. get blendSrc() {
  20686. return this._shaderValues.getInt(PixelLineMaterial.BLEND_SRC);
  20687. }
  20688. set blendDst(value) {
  20689. this._shaderValues.setInt(PixelLineMaterial.BLEND_DST, value);
  20690. }
  20691. get blendDst() {
  20692. return this._shaderValues.getInt(PixelLineMaterial.BLEND_DST);
  20693. }
  20694. set depthTest(value) {
  20695. this._shaderValues.setInt(PixelLineMaterial.DEPTH_TEST, value);
  20696. }
  20697. get depthTest() {
  20698. return this._shaderValues.getInt(PixelLineMaterial.DEPTH_TEST);
  20699. }
  20700. clone() {
  20701. var dest = new PixelLineMaterial();
  20702. this.cloneTo(dest);
  20703. return dest;
  20704. }
  20705. }
  20706. PixelLineMaterial.COLOR = Shader3D.propertyNameToID("u_Color");
  20707. PixelLineMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  20708. PixelLineMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  20709. PixelLineMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  20710. PixelLineMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  20711. PixelLineMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  20712. PixelLineMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  20713. class PixelLineVertex {
  20714. static get vertexDeclaration() {
  20715. return PixelLineVertex._vertexDeclaration;
  20716. }
  20717. static __init__() {
  20718. PixelLineVertex._vertexDeclaration = new VertexDeclaration(28, [new VertexElement(0, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0),
  20719. new VertexElement(12, VertexElementFormat.Vector4, VertexMesh.MESH_COLOR0)]);
  20720. }
  20721. get vertexDeclaration() {
  20722. return PixelLineVertex._vertexDeclaration;
  20723. }
  20724. constructor() {
  20725. }
  20726. }
  20727. class CastShadowList extends SingletonList {
  20728. constructor() {
  20729. super();
  20730. }
  20731. add(element) {
  20732. var index = element._indexInCastShadowList;
  20733. if (index !== -1)
  20734. throw "CastShadowList:element has in CastShadowList.";
  20735. this._add(element);
  20736. element._indexInCastShadowList = this.length++;
  20737. }
  20738. remove(element) {
  20739. var index = element._indexInCastShadowList;
  20740. this.length--;
  20741. if (index !== this.length) {
  20742. var end = this.elements[this.length];
  20743. this.elements[index] = end;
  20744. end._indexInCastShadowList = index;
  20745. }
  20746. element._indexInCastShadowList = -1;
  20747. }
  20748. }
  20749. class SimpleSingletonList extends SingletonList {
  20750. constructor() {
  20751. super();
  20752. }
  20753. add(element) {
  20754. var index = element._getIndexInList();
  20755. if (index !== -1)
  20756. throw "SimpleSingletonList:" + element + " has in SingletonList.";
  20757. this._add(element);
  20758. element._setIndexInList(this.length++);
  20759. }
  20760. remove(element) {
  20761. var index = element._getIndexInList();
  20762. this.length--;
  20763. if (index !== this.length) {
  20764. var end = this.elements[this.length];
  20765. this.elements[index] = end;
  20766. end._setIndexInList(index);
  20767. }
  20768. element._setIndexInList(-1);
  20769. }
  20770. }
  20771. class MouseTouch {
  20772. constructor() {
  20773. this._pressedSprite = null;
  20774. this._pressedLoopCount = -1;
  20775. this.sprite = null;
  20776. this.mousePositionX = 0;
  20777. this.mousePositionY = 0;
  20778. }
  20779. }
  20780. class Touch {
  20781. constructor() {
  20782. this._indexInList = -1;
  20783. this._identifier = -1;
  20784. this._position = new Vector2();
  20785. }
  20786. get identifier() {
  20787. return this._identifier;
  20788. }
  20789. get position() {
  20790. return this._position;
  20791. }
  20792. _getIndexInList() {
  20793. return this._indexInList;
  20794. }
  20795. _setIndexInList(index) {
  20796. this._indexInList = index;
  20797. }
  20798. }
  20799. class HitResult {
  20800. constructor() {
  20801. this.succeeded = false;
  20802. this.collider = null;
  20803. this.point = new Vector3();
  20804. this.normal = new Vector3();
  20805. this.hitFraction = 0;
  20806. }
  20807. }
  20808. class PhysicsUpdateList extends SingletonList {
  20809. constructor() {
  20810. super();
  20811. }
  20812. add(element) {
  20813. var index = element._inPhysicUpdateListIndex;
  20814. if (index !== -1)
  20815. throw "PhysicsUpdateList:element has in PhysicsUpdateList.";
  20816. this._add(element);
  20817. element._inPhysicUpdateListIndex = this.length++;
  20818. }
  20819. remove(element) {
  20820. var index = element._inPhysicUpdateListIndex;
  20821. this.length--;
  20822. if (index !== this.length) {
  20823. var end = this.elements[this.length];
  20824. this.elements[index] = end;
  20825. end._inPhysicUpdateListIndex = index;
  20826. }
  20827. element._inPhysicUpdateListIndex = -1;
  20828. }
  20829. }
  20830. class ContactPoint {
  20831. constructor() {
  20832. this._idCounter = 0;
  20833. this.colliderA = null;
  20834. this.colliderB = null;
  20835. this.distance = 0;
  20836. this.normal = new Vector3();
  20837. this.positionOnA = new Vector3();
  20838. this.positionOnB = new Vector3();
  20839. this._id = ++this._idCounter;
  20840. }
  20841. }
  20842. class Collision {
  20843. constructor() {
  20844. this._lastUpdateFrame = -2147483648;
  20845. this._updateFrame = -2147483648;
  20846. this._isTrigger = false;
  20847. this.contacts = [];
  20848. }
  20849. _setUpdateFrame(farme) {
  20850. this._lastUpdateFrame = this._updateFrame;
  20851. this._updateFrame = farme;
  20852. }
  20853. }
  20854. class CollisionTool {
  20855. constructor() {
  20856. this._hitResultsPoolIndex = 0;
  20857. this._hitResultsPool = [];
  20858. this._contactPonintsPoolIndex = 0;
  20859. this._contactPointsPool = [];
  20860. this._collisionsPool = [];
  20861. this._collisions = {};
  20862. }
  20863. getHitResult() {
  20864. var hitResult = this._hitResultsPool[this._hitResultsPoolIndex++];
  20865. if (!hitResult) {
  20866. hitResult = new HitResult();
  20867. this._hitResultsPool.push(hitResult);
  20868. }
  20869. return hitResult;
  20870. }
  20871. recoverAllHitResultsPool() {
  20872. this._hitResultsPoolIndex = 0;
  20873. }
  20874. getContactPoints() {
  20875. var contactPoint = this._contactPointsPool[this._contactPonintsPoolIndex++];
  20876. if (!contactPoint) {
  20877. contactPoint = new ContactPoint();
  20878. this._contactPointsPool.push(contactPoint);
  20879. }
  20880. return contactPoint;
  20881. }
  20882. recoverAllContactPointsPool() {
  20883. this._contactPonintsPoolIndex = 0;
  20884. }
  20885. getCollision(physicComponentA, physicComponentB) {
  20886. var collision;
  20887. var idA = physicComponentA.id;
  20888. var idB = physicComponentB.id;
  20889. var subCollisionFirst = this._collisions[idA];
  20890. if (subCollisionFirst)
  20891. collision = subCollisionFirst[idB];
  20892. if (!collision) {
  20893. if (!subCollisionFirst) {
  20894. subCollisionFirst = {};
  20895. this._collisions[idA] = subCollisionFirst;
  20896. }
  20897. collision = this._collisionsPool.length === 0 ? new Collision() : this._collisionsPool.pop();
  20898. collision._colliderA = physicComponentA;
  20899. collision._colliderB = physicComponentB;
  20900. subCollisionFirst[idB] = collision;
  20901. }
  20902. return collision;
  20903. }
  20904. recoverCollision(collision) {
  20905. var idA = collision._colliderA.id;
  20906. var idB = collision._colliderB.id;
  20907. this._collisions[idA][idB] = null;
  20908. this._collisionsPool.push(collision);
  20909. }
  20910. garbageCollection() {
  20911. this._hitResultsPoolIndex = 0;
  20912. this._hitResultsPool.length = 0;
  20913. this._contactPonintsPoolIndex = 0;
  20914. this._contactPointsPool.length = 0;
  20915. this._collisionsPool.length = 0;
  20916. for (var subCollisionsKey in this._collisionsPool) {
  20917. var subCollisions = this._collisionsPool[subCollisionsKey];
  20918. var wholeDelete = true;
  20919. for (var collisionKey in subCollisions) {
  20920. if (subCollisions[collisionKey])
  20921. wholeDelete = false;
  20922. else
  20923. delete subCollisions[collisionKey];
  20924. }
  20925. if (wholeDelete)
  20926. delete this._collisionsPool[subCollisionsKey];
  20927. }
  20928. }
  20929. }
  20930. class Physics3D {
  20931. }
  20932. Physics3D._physics3D = null;
  20933. Physics3D._enbalePhysics = false;
  20934. class ColliderShape {
  20935. constructor() {
  20936. this._scale = new Vector3(1, 1, 1);
  20937. this._centerMatrix = new Matrix4x4();
  20938. this._attatched = false;
  20939. this._indexInCompound = -1;
  20940. this._compoundParent = null;
  20941. this._attatchedCollisionObject = null;
  20942. this._referenceCount = 0;
  20943. this._localOffset = new Vector3(0, 0, 0);
  20944. this._localRotation = new Quaternion(0, 0, 0, 1);
  20945. this.needsCustomCollisionCallback = false;
  20946. }
  20947. static __init__() {
  20948. ColliderShape._nativeScale = new Physics3D._physics3D.btVector3(1, 1, 1);
  20949. ColliderShape._nativeVector30 = new Physics3D._physics3D.btVector3(0, 0, 0);
  20950. ColliderShape._nativQuaternion0 = new Physics3D._physics3D.btQuaternion(0, 0, 0, 1);
  20951. ColliderShape._nativeTransform0 = new Physics3D._physics3D.btTransform();
  20952. }
  20953. static _createAffineTransformation(trans, rot, outE) {
  20954. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  20955. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  20956. var wx = w * x2, wy = w * y2, wz = w * z2;
  20957. outE[0] = (1 - (yy + zz));
  20958. outE[1] = (xy + wz);
  20959. outE[2] = (xz - wy);
  20960. outE[3] = 0;
  20961. outE[4] = (xy - wz);
  20962. outE[5] = (1 - (xx + zz));
  20963. outE[6] = (yz + wx);
  20964. outE[7] = 0;
  20965. outE[8] = (xz + wy);
  20966. outE[9] = (yz - wx);
  20967. outE[10] = (1 - (xx + yy));
  20968. outE[11] = 0;
  20969. outE[12] = trans.x;
  20970. outE[13] = trans.y;
  20971. outE[14] = trans.z;
  20972. outE[15] = 1;
  20973. }
  20974. get type() {
  20975. return this._type;
  20976. }
  20977. get localOffset() {
  20978. return this._localOffset;
  20979. }
  20980. set localOffset(value) {
  20981. this._localOffset = value;
  20982. if (this._compoundParent)
  20983. this._compoundParent._updateChildTransform(this);
  20984. }
  20985. get localRotation() {
  20986. return this._localRotation;
  20987. }
  20988. set localRotation(value) {
  20989. this._localRotation = value;
  20990. if (this._compoundParent)
  20991. this._compoundParent._updateChildTransform(this);
  20992. }
  20993. _setScale(value) {
  20994. if (this._compoundParent) {
  20995. this.updateLocalTransformations();
  20996. }
  20997. else {
  20998. ColliderShape._nativeScale.setValue(value.x, value.y, value.z);
  20999. this._nativeShape.setLocalScaling(ColliderShape._nativeScale);
  21000. }
  21001. }
  21002. _addReference() {
  21003. this._referenceCount++;
  21004. }
  21005. _removeReference() {
  21006. this._referenceCount--;
  21007. }
  21008. updateLocalTransformations() {
  21009. if (this._compoundParent) {
  21010. var offset = ColliderShape._tempVector30;
  21011. Vector3.multiply(this.localOffset, this._scale, offset);
  21012. ColliderShape._createAffineTransformation(offset, this.localRotation, this._centerMatrix.elements);
  21013. }
  21014. else {
  21015. ColliderShape._createAffineTransformation(this.localOffset, this.localRotation, this._centerMatrix.elements);
  21016. }
  21017. }
  21018. cloneTo(destObject) {
  21019. var destColliderShape = destObject;
  21020. this._localOffset.cloneTo(destColliderShape.localOffset);
  21021. this._localRotation.cloneTo(destColliderShape.localRotation);
  21022. destColliderShape.localOffset = destColliderShape.localOffset;
  21023. destColliderShape.localRotation = destColliderShape.localRotation;
  21024. }
  21025. clone() {
  21026. return null;
  21027. }
  21028. destroy() {
  21029. if (this._nativeShape) {
  21030. Physics3D._physics3D.destroy(this._nativeShape);
  21031. this._nativeShape = null;
  21032. }
  21033. }
  21034. }
  21035. ColliderShape.SHAPEORIENTATION_UPX = 0;
  21036. ColliderShape.SHAPEORIENTATION_UPY = 1;
  21037. ColliderShape.SHAPEORIENTATION_UPZ = 2;
  21038. ColliderShape.SHAPETYPES_BOX = 0;
  21039. ColliderShape.SHAPETYPES_SPHERE = 1;
  21040. ColliderShape.SHAPETYPES_CYLINDER = 2;
  21041. ColliderShape.SHAPETYPES_CAPSULE = 3;
  21042. ColliderShape.SHAPETYPES_CONVEXHULL = 4;
  21043. ColliderShape.SHAPETYPES_COMPOUND = 5;
  21044. ColliderShape.SHAPETYPES_STATICPLANE = 6;
  21045. ColliderShape.SHAPETYPES_CONE = 7;
  21046. ColliderShape._tempVector30 = new Vector3();
  21047. class BoxColliderShape extends ColliderShape {
  21048. static __init__() {
  21049. BoxColliderShape._nativeSize = new Physics3D._physics3D.btVector3(0, 0, 0);
  21050. }
  21051. get sizeX() {
  21052. return this._sizeX;
  21053. }
  21054. get sizeY() {
  21055. return this._sizeY;
  21056. }
  21057. get sizeZ() {
  21058. return this._sizeZ;
  21059. }
  21060. constructor(sizeX = 1.0, sizeY = 1.0, sizeZ = 1.0) {
  21061. super();
  21062. this._sizeX = sizeX;
  21063. this._sizeY = sizeY;
  21064. this._sizeZ = sizeZ;
  21065. this._type = ColliderShape.SHAPETYPES_BOX;
  21066. BoxColliderShape._nativeSize.setValue(sizeX / 2, sizeY / 2, sizeZ / 2);
  21067. this._nativeShape = new Physics3D._physics3D.btBoxShape(BoxColliderShape._nativeSize);
  21068. }
  21069. clone() {
  21070. var dest = new BoxColliderShape(this._sizeX, this._sizeY, this._sizeZ);
  21071. this.cloneTo(dest);
  21072. return dest;
  21073. }
  21074. }
  21075. class CapsuleColliderShape extends ColliderShape {
  21076. constructor(radius = 0.5, length = 1.25, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  21077. super();
  21078. this._radius = radius;
  21079. this._length = length;
  21080. this._orientation = orientation;
  21081. this._type = ColliderShape.SHAPETYPES_CAPSULE;
  21082. switch (orientation) {
  21083. case ColliderShape.SHAPEORIENTATION_UPX:
  21084. this._nativeShape = new Physics3D._physics3D.btCapsuleShapeX(radius, length - radius * 2);
  21085. break;
  21086. case ColliderShape.SHAPEORIENTATION_UPY:
  21087. this._nativeShape = new Physics3D._physics3D.btCapsuleShape(radius, length - radius * 2);
  21088. break;
  21089. case ColliderShape.SHAPEORIENTATION_UPZ:
  21090. this._nativeShape = new Physics3D._physics3D.btCapsuleShapeZ(radius, length - radius * 2);
  21091. break;
  21092. default:
  21093. throw "CapsuleColliderShape:unknown orientation.";
  21094. }
  21095. }
  21096. get radius() {
  21097. return this._radius;
  21098. }
  21099. get length() {
  21100. return this._length;
  21101. }
  21102. get orientation() {
  21103. return this._orientation;
  21104. }
  21105. _setScale(value) {
  21106. var fixScale = CapsuleColliderShape._tempVector30;
  21107. switch (this.orientation) {
  21108. case ColliderShape.SHAPEORIENTATION_UPX:
  21109. fixScale.x = value.x;
  21110. fixScale.y = fixScale.z = Math.max(value.y, value.z);
  21111. break;
  21112. case ColliderShape.SHAPEORIENTATION_UPY:
  21113. fixScale.y = value.y;
  21114. fixScale.x = fixScale.z = Math.max(value.x, value.z);
  21115. break;
  21116. case ColliderShape.SHAPEORIENTATION_UPZ:
  21117. fixScale.z = value.z;
  21118. fixScale.x = fixScale.y = Math.max(value.x, value.y);
  21119. break;
  21120. default:
  21121. throw "CapsuleColliderShape:unknown orientation.";
  21122. }
  21123. super._setScale(fixScale);
  21124. }
  21125. clone() {
  21126. var dest = new CapsuleColliderShape(this._radius, this._length, this._orientation);
  21127. this.cloneTo(dest);
  21128. return dest;
  21129. }
  21130. }
  21131. CapsuleColliderShape._tempVector30 = new Vector3();
  21132. class CompoundColliderShape extends ColliderShape {
  21133. constructor() {
  21134. super();
  21135. this._childColliderShapes = [];
  21136. this._type = ColliderShape.SHAPETYPES_COMPOUND;
  21137. this._nativeShape = new Physics3D._physics3D.btCompoundShape();
  21138. }
  21139. static __init__() {
  21140. CompoundColliderShape._nativeVector3One = new Physics3D._physics3D.btVector3(1, 1, 1);
  21141. CompoundColliderShape._nativeTransform = new Physics3D._physics3D.btTransform();
  21142. CompoundColliderShape._nativeOffset = new Physics3D._physics3D.btVector3(0, 0, 0);
  21143. CompoundColliderShape._nativRotation = new Physics3D._physics3D.btQuaternion(0, 0, 0, 1);
  21144. }
  21145. _clearChildShape(shape) {
  21146. shape._attatched = false;
  21147. shape._compoundParent = null;
  21148. shape._indexInCompound = -1;
  21149. }
  21150. _addReference() {
  21151. }
  21152. _removeReference() {
  21153. }
  21154. _updateChildTransform(shape) {
  21155. var offset = shape.localOffset;
  21156. var rotation = shape.localRotation;
  21157. var nativeOffset = ColliderShape._nativeVector30;
  21158. var nativeQuaternion = ColliderShape._nativQuaternion0;
  21159. var nativeTransform = ColliderShape._nativeTransform0;
  21160. nativeOffset.setValue(-offset.x, offset.y, offset.z);
  21161. nativeQuaternion.setValue(-rotation.x, rotation.y, rotation.z, -rotation.w);
  21162. nativeTransform.setOrigin(nativeOffset);
  21163. nativeTransform.setRotation(nativeQuaternion);
  21164. this._nativeShape.updateChildTransform(shape._indexInCompound, nativeTransform, true);
  21165. }
  21166. addChildShape(shape) {
  21167. if (shape._attatched)
  21168. throw "CompoundColliderShape: this shape has attatched to other entity.";
  21169. shape._attatched = true;
  21170. shape._compoundParent = this;
  21171. shape._indexInCompound = this._childColliderShapes.length;
  21172. this._childColliderShapes.push(shape);
  21173. var offset = shape.localOffset;
  21174. var rotation = shape.localRotation;
  21175. CompoundColliderShape._nativeOffset.setValue(-offset.x, offset.y, offset.z);
  21176. CompoundColliderShape._nativRotation.setValue(-rotation.x, rotation.y, rotation.z, -rotation.w);
  21177. CompoundColliderShape._nativeTransform.setOrigin(CompoundColliderShape._nativeOffset);
  21178. CompoundColliderShape._nativeTransform.setRotation(CompoundColliderShape._nativRotation);
  21179. var nativeScale = this._nativeShape.getLocalScaling();
  21180. this._nativeShape.setLocalScaling(CompoundColliderShape._nativeVector3One);
  21181. this._nativeShape.addChildShape(CompoundColliderShape._nativeTransform, shape._nativeShape);
  21182. this._nativeShape.setLocalScaling(nativeScale);
  21183. (this._attatchedCollisionObject) && (this._attatchedCollisionObject.colliderShape = this);
  21184. }
  21185. removeChildShape(shape) {
  21186. if (shape._compoundParent === this) {
  21187. var index = shape._indexInCompound;
  21188. this._clearChildShape(shape);
  21189. var endShape = this._childColliderShapes[this._childColliderShapes.length - 1];
  21190. endShape._indexInCompound = index;
  21191. this._childColliderShapes[index] = endShape;
  21192. this._childColliderShapes.pop();
  21193. this._nativeShape.removeChildShapeByIndex(index);
  21194. }
  21195. }
  21196. clearChildShape() {
  21197. for (var i = 0, n = this._childColliderShapes.length; i < n; i++) {
  21198. this._clearChildShape(this._childColliderShapes[i]);
  21199. this._nativeShape.removeChildShapeByIndex(0);
  21200. }
  21201. this._childColliderShapes.length = 0;
  21202. }
  21203. getChildShapeCount() {
  21204. return this._childColliderShapes.length;
  21205. }
  21206. cloneTo(destObject) {
  21207. var destCompoundColliderShape = destObject;
  21208. destCompoundColliderShape.clearChildShape();
  21209. for (var i = 0, n = this._childColliderShapes.length; i < n; i++)
  21210. destCompoundColliderShape.addChildShape(this._childColliderShapes[i].clone());
  21211. }
  21212. clone() {
  21213. var dest = new CompoundColliderShape();
  21214. this.cloneTo(dest);
  21215. return dest;
  21216. }
  21217. destroy() {
  21218. super.destroy();
  21219. for (var i = 0, n = this._childColliderShapes.length; i < n; i++) {
  21220. var childShape = this._childColliderShapes[i];
  21221. if (childShape._referenceCount === 0)
  21222. childShape.destroy();
  21223. }
  21224. }
  21225. }
  21226. class ConeColliderShape extends ColliderShape {
  21227. constructor(radius = 0.5, height = 1.0, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  21228. super();
  21229. this._radius = 1;
  21230. this._height = 0.5;
  21231. this._radius = radius;
  21232. this._height = height;
  21233. this._orientation = orientation;
  21234. this._type = ColliderShape.SHAPETYPES_CYLINDER;
  21235. switch (orientation) {
  21236. case ColliderShape.SHAPEORIENTATION_UPX:
  21237. this._nativeShape = new Physics3D._physics3D.btConeShapeX(radius, height);
  21238. break;
  21239. case ColliderShape.SHAPEORIENTATION_UPY:
  21240. this._nativeShape = new Physics3D._physics3D.btConeShape(radius, height);
  21241. break;
  21242. case ColliderShape.SHAPEORIENTATION_UPZ:
  21243. this._nativeShape = new Physics3D._physics3D.btConeShapeZ(radius, height);
  21244. break;
  21245. default:
  21246. throw "ConeColliderShape:unknown orientation.";
  21247. }
  21248. }
  21249. get radius() {
  21250. return this._radius;
  21251. }
  21252. get height() {
  21253. return this._height;
  21254. }
  21255. get orientation() {
  21256. return this._orientation;
  21257. }
  21258. clone() {
  21259. var dest = new ConeColliderShape(this._radius, this._height, this._orientation);
  21260. this.cloneTo(dest);
  21261. return dest;
  21262. }
  21263. }
  21264. class CylinderColliderShape extends ColliderShape {
  21265. constructor(radius = 0.5, height = 1.0, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  21266. super();
  21267. this._radius = 1;
  21268. this._height = 0.5;
  21269. this._radius = radius;
  21270. this._height = height;
  21271. this._orientation = orientation;
  21272. this._type = ColliderShape.SHAPETYPES_CYLINDER;
  21273. switch (orientation) {
  21274. case ColliderShape.SHAPEORIENTATION_UPX:
  21275. CylinderColliderShape._nativeSize.setValue(height / 2, radius, radius);
  21276. this._nativeShape = new Physics3D._physics3D.btCylinderShapeX(CylinderColliderShape._nativeSize);
  21277. break;
  21278. case ColliderShape.SHAPEORIENTATION_UPY:
  21279. CylinderColliderShape._nativeSize.setValue(radius, height / 2, radius);
  21280. this._nativeShape = new Physics3D._physics3D.btCylinderShape(CylinderColliderShape._nativeSize);
  21281. break;
  21282. case ColliderShape.SHAPEORIENTATION_UPZ:
  21283. CylinderColliderShape._nativeSize.setValue(radius, radius, height / 2);
  21284. this._nativeShape = new Physics3D._physics3D.btCylinderShapeZ(CylinderColliderShape._nativeSize);
  21285. break;
  21286. default:
  21287. throw "CapsuleColliderShape:unknown orientation.";
  21288. }
  21289. }
  21290. static __init__() {
  21291. CylinderColliderShape._nativeSize = new Physics3D._physics3D.btVector3(0, 0, 0);
  21292. }
  21293. get radius() {
  21294. return this._radius;
  21295. }
  21296. get height() {
  21297. return this._height;
  21298. }
  21299. get orientation() {
  21300. return this._orientation;
  21301. }
  21302. clone() {
  21303. var dest = new CylinderColliderShape(this._radius, this._height, this._orientation);
  21304. this.cloneTo(dest);
  21305. return dest;
  21306. }
  21307. }
  21308. class MeshColliderShape extends ColliderShape {
  21309. constructor() {
  21310. super();
  21311. this._mesh = null;
  21312. this._convex = false;
  21313. }
  21314. get mesh() {
  21315. return this._mesh;
  21316. }
  21317. set mesh(value) {
  21318. if (this._mesh !== value) {
  21319. var physics3D = Physics3D._physics3D;
  21320. if (this._mesh) {
  21321. physics3D.destroy(this._nativeShape);
  21322. }
  21323. if (value) {
  21324. this._nativeShape = new Physics3D._physics3D.btGImpactMeshShape(value._getPhysicMesh());
  21325. this._nativeShape.updateBound();
  21326. }
  21327. this._mesh = value;
  21328. }
  21329. }
  21330. get convex() {
  21331. return this._convex;
  21332. }
  21333. set convex(value) {
  21334. this._convex = value;
  21335. }
  21336. _setScale(value) {
  21337. if (this._compoundParent) {
  21338. this.updateLocalTransformations();
  21339. }
  21340. else {
  21341. ColliderShape._nativeScale.setValue(value.x, value.y, value.z);
  21342. this._nativeShape.setLocalScaling(ColliderShape._nativeScale);
  21343. this._nativeShape.updateBound();
  21344. }
  21345. }
  21346. cloneTo(destObject) {
  21347. var destMeshCollider = destObject;
  21348. destMeshCollider.convex = this._convex;
  21349. destMeshCollider.mesh = this._mesh;
  21350. super.cloneTo(destObject);
  21351. }
  21352. clone() {
  21353. var dest = new MeshColliderShape();
  21354. this.cloneTo(dest);
  21355. return dest;
  21356. }
  21357. destroy() {
  21358. if (this._nativeShape) {
  21359. var physics3D = Physics3D._physics3D;
  21360. physics3D.destroy(this._nativeShape);
  21361. this._nativeShape = null;
  21362. }
  21363. }
  21364. }
  21365. class SphereColliderShape extends ColliderShape {
  21366. get radius() {
  21367. return this._radius;
  21368. }
  21369. constructor(radius = 0.5) {
  21370. super();
  21371. this._radius = radius;
  21372. this._type = ColliderShape.SHAPETYPES_SPHERE;
  21373. this._nativeShape = new Physics3D._physics3D.btSphereShape(radius);
  21374. }
  21375. clone() {
  21376. var dest = new SphereColliderShape(this._radius);
  21377. this.cloneTo(dest);
  21378. return dest;
  21379. }
  21380. }
  21381. class PhysicsComponent extends Laya.Component {
  21382. constructor(collisionGroup, canCollideWith) {
  21383. super();
  21384. this._restitution = 0.0;
  21385. this._friction = 0.5;
  21386. this._rollingFriction = 0.0;
  21387. this._ccdMotionThreshold = 0.0;
  21388. this._ccdSweptSphereRadius = 0.0;
  21389. this._collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER;
  21390. this._canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER;
  21391. this._colliderShape = null;
  21392. this._transformFlag = 2147483647;
  21393. this._enableProcessCollisions = true;
  21394. this._inPhysicUpdateListIndex = -1;
  21395. this.canScaleShape = true;
  21396. this._collisionGroup = collisionGroup;
  21397. this._canCollideWith = canCollideWith;
  21398. PhysicsComponent._physicObjectsMap[this.id] = this;
  21399. }
  21400. static __init__() {
  21401. PhysicsComponent._nativeVector30 = new Physics3D._physics3D.btVector3(0, 0, 0);
  21402. PhysicsComponent._nativeQuaternion0 = new Physics3D._physics3D.btQuaternion(0, 0, 0, 1);
  21403. }
  21404. static _createAffineTransformationArray(tranX, tranY, tranZ, rotX, rotY, rotZ, rotW, scale, outE) {
  21405. var x2 = rotX + rotX, y2 = rotY + rotY, z2 = rotZ + rotZ;
  21406. var xx = rotX * x2, xy = rotX * y2, xz = rotX * z2, yy = rotY * y2, yz = rotY * z2, zz = rotZ * z2;
  21407. var wx = rotW * x2, wy = rotW * y2, wz = rotW * z2, sx = scale[0], sy = scale[1], sz = scale[2];
  21408. outE[0] = (1 - (yy + zz)) * sx;
  21409. outE[1] = (xy + wz) * sx;
  21410. outE[2] = (xz - wy) * sx;
  21411. outE[3] = 0;
  21412. outE[4] = (xy - wz) * sy;
  21413. outE[5] = (1 - (xx + zz)) * sy;
  21414. outE[6] = (yz + wx) * sy;
  21415. outE[7] = 0;
  21416. outE[8] = (xz + wy) * sz;
  21417. outE[9] = (yz - wx) * sz;
  21418. outE[10] = (1 - (xx + yy)) * sz;
  21419. outE[11] = 0;
  21420. outE[12] = tranX;
  21421. outE[13] = tranY;
  21422. outE[14] = tranZ;
  21423. outE[15] = 1;
  21424. }
  21425. static _creatShape(shapeData) {
  21426. var colliderShape;
  21427. switch (shapeData.type) {
  21428. case "BoxColliderShape":
  21429. var sizeData = shapeData.size;
  21430. colliderShape = sizeData ? new BoxColliderShape(sizeData[0], sizeData[1], sizeData[2]) : new BoxColliderShape();
  21431. break;
  21432. case "SphereColliderShape":
  21433. colliderShape = new SphereColliderShape(shapeData.radius);
  21434. break;
  21435. case "CapsuleColliderShape":
  21436. colliderShape = new CapsuleColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  21437. break;
  21438. case "MeshColliderShape":
  21439. var meshCollider = new MeshColliderShape();
  21440. shapeData.mesh && (meshCollider.mesh = Laya.Loader.getRes(shapeData.mesh));
  21441. colliderShape = meshCollider;
  21442. break;
  21443. case "ConeColliderShape":
  21444. colliderShape = new ConeColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  21445. break;
  21446. case "CylinderColliderShape":
  21447. colliderShape = new CylinderColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  21448. break;
  21449. default:
  21450. throw "unknown shape type.";
  21451. }
  21452. if (shapeData.center) {
  21453. var localOffset = colliderShape.localOffset;
  21454. localOffset.fromArray(shapeData.center);
  21455. colliderShape.localOffset = localOffset;
  21456. }
  21457. return colliderShape;
  21458. }
  21459. static physicVector3TransformQuat(source, qx, qy, qz, qw, out) {
  21460. 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;
  21461. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  21462. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  21463. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  21464. }
  21465. static physicQuaternionMultiply(lx, ly, lz, lw, right, out) {
  21466. var rx = right.x;
  21467. var ry = right.y;
  21468. var rz = right.z;
  21469. var rw = right.w;
  21470. var a = (ly * rz - lz * ry);
  21471. var b = (lz * rx - lx * rz);
  21472. var c = (lx * ry - ly * rx);
  21473. var d = (lx * rx + ly * ry + lz * rz);
  21474. out.x = (lx * rw + rx * lw) + a;
  21475. out.y = (ly * rw + ry * lw) + b;
  21476. out.z = (lz * rw + rz * lw) + c;
  21477. out.w = lw * rw - d;
  21478. }
  21479. get restitution() {
  21480. return this._restitution;
  21481. }
  21482. set restitution(value) {
  21483. this._restitution = value;
  21484. this._nativeColliderObject && this._nativeColliderObject.setRestitution(value);
  21485. }
  21486. get friction() {
  21487. return this._friction;
  21488. }
  21489. set friction(value) {
  21490. this._friction = value;
  21491. this._nativeColliderObject && this._nativeColliderObject.setFriction(value);
  21492. }
  21493. get rollingFriction() {
  21494. return this._nativeColliderObject.getRollingFriction();
  21495. }
  21496. set rollingFriction(value) {
  21497. this._rollingFriction = value;
  21498. this._nativeColliderObject && this._nativeColliderObject.setRollingFriction(value);
  21499. }
  21500. get ccdMotionThreshold() {
  21501. return this._ccdMotionThreshold;
  21502. }
  21503. set ccdMotionThreshold(value) {
  21504. this._ccdMotionThreshold = value;
  21505. this._nativeColliderObject && this._nativeColliderObject.setCcdMotionThreshold(value);
  21506. }
  21507. get ccdSweptSphereRadius() {
  21508. return this._ccdSweptSphereRadius;
  21509. }
  21510. set ccdSweptSphereRadius(value) {
  21511. this._ccdSweptSphereRadius = value;
  21512. this._nativeColliderObject && this._nativeColliderObject.setCcdSweptSphereRadius(value);
  21513. }
  21514. get isActive() {
  21515. return this._nativeColliderObject ? this._nativeColliderObject.isActive() : false;
  21516. }
  21517. get enabled() {
  21518. return super.enabled;
  21519. }
  21520. set enabled(value) {
  21521. if (this._enabled != value) {
  21522. if (this._simulation && this._colliderShape) {
  21523. if (value) {
  21524. this._derivePhysicsTransformation(true);
  21525. this._addToSimulation();
  21526. }
  21527. else {
  21528. this._removeFromSimulation();
  21529. }
  21530. }
  21531. super.enabled = value;
  21532. }
  21533. }
  21534. get colliderShape() {
  21535. return this._colliderShape;
  21536. }
  21537. set colliderShape(value) {
  21538. var lastColliderShape = this._colliderShape;
  21539. if (lastColliderShape) {
  21540. lastColliderShape._attatched = false;
  21541. lastColliderShape._attatchedCollisionObject = null;
  21542. }
  21543. this._colliderShape = value;
  21544. if (value) {
  21545. if (value._attatched) {
  21546. throw "PhysicsComponent: this shape has attatched to other entity.";
  21547. }
  21548. else {
  21549. value._attatched = true;
  21550. value._attatchedCollisionObject = this;
  21551. }
  21552. if (this._nativeColliderObject) {
  21553. this._nativeColliderObject.setCollisionShape(value._nativeShape);
  21554. var canInSimulation = this._simulation && this._enabled;
  21555. (canInSimulation && lastColliderShape) && (this._removeFromSimulation());
  21556. this._onShapeChange(value);
  21557. if (canInSimulation) {
  21558. this._derivePhysicsTransformation(true);
  21559. this._addToSimulation();
  21560. }
  21561. }
  21562. }
  21563. else {
  21564. if (this._simulation && this._enabled)
  21565. lastColliderShape && this._removeFromSimulation();
  21566. }
  21567. }
  21568. get simulation() {
  21569. return this._simulation;
  21570. }
  21571. get collisionGroup() {
  21572. return this._collisionGroup;
  21573. }
  21574. set collisionGroup(value) {
  21575. if (this._collisionGroup !== value) {
  21576. this._collisionGroup = value;
  21577. if (this._simulation && this._colliderShape && this._enabled) {
  21578. this._removeFromSimulation();
  21579. this._addToSimulation();
  21580. }
  21581. }
  21582. }
  21583. get canCollideWith() {
  21584. return this._canCollideWith;
  21585. }
  21586. set canCollideWith(value) {
  21587. if (this._canCollideWith !== value) {
  21588. this._canCollideWith = value;
  21589. if (this._simulation && this._colliderShape && this._enabled) {
  21590. this._removeFromSimulation();
  21591. this._addToSimulation();
  21592. }
  21593. }
  21594. }
  21595. _isValid() {
  21596. return this._simulation && this._colliderShape && this._enabled;
  21597. }
  21598. _parse(data) {
  21599. (data.collisionGroup != null) && (this.collisionGroup = data.collisionGroup);
  21600. (data.canCollideWith != null) && (this.canCollideWith = data.canCollideWith);
  21601. (data.ccdMotionThreshold != null) && (this.ccdMotionThreshold = data.ccdMotionThreshold);
  21602. (data.ccdSweptSphereRadius != null) && (this.ccdSweptSphereRadius = data.ccdSweptSphereRadius);
  21603. }
  21604. _parseShape(shapesData) {
  21605. var shapeCount = shapesData.length;
  21606. if (shapeCount === 1) {
  21607. var shape = PhysicsComponent._creatShape(shapesData[0]);
  21608. this.colliderShape = shape;
  21609. }
  21610. else {
  21611. var compoundShape = new CompoundColliderShape();
  21612. for (var i = 0; i < shapeCount; i++) {
  21613. shape = PhysicsComponent._creatShape(shapesData[i]);
  21614. compoundShape.addChildShape(shape);
  21615. }
  21616. this.colliderShape = compoundShape;
  21617. }
  21618. }
  21619. _onScaleChange(scale) {
  21620. this._colliderShape._setScale(scale);
  21621. }
  21622. _setTransformFlag(type, value) {
  21623. if (value)
  21624. this._transformFlag |= type;
  21625. else
  21626. this._transformFlag &= ~type;
  21627. }
  21628. _getTransformFlag(type) {
  21629. return (this._transformFlag & type) != 0;
  21630. }
  21631. _addToSimulation() {
  21632. }
  21633. _removeFromSimulation() {
  21634. }
  21635. _derivePhysicsTransformation(force) {
  21636. this._innerDerivePhysicsTransformation(this._nativeColliderObject.getWorldTransform(), force);
  21637. }
  21638. _innerDerivePhysicsTransformation(physicTransformOut, force) {
  21639. var transform = this.owner._transform;
  21640. var rotation = transform.rotation;
  21641. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  21642. var shapeOffset = this._colliderShape.localOffset;
  21643. var position = transform.position;
  21644. var nativePosition = PhysicsComponent._nativeVector30;
  21645. if (shapeOffset.x !== 0 || shapeOffset.y !== 0 || shapeOffset.z !== 0) {
  21646. var physicPosition = PhysicsComponent._tempVector30;
  21647. PhysicsComponent.physicVector3TransformQuat(shapeOffset, rotation.x, rotation.y, rotation.z, rotation.w, physicPosition);
  21648. Vector3.add(position, physicPosition, physicPosition);
  21649. nativePosition.setValue(-physicPosition.x, physicPosition.y, physicPosition.z);
  21650. }
  21651. else {
  21652. nativePosition.setValue(-position.x, position.y, position.z);
  21653. }
  21654. physicTransformOut.setOrigin(nativePosition);
  21655. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  21656. }
  21657. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION)) {
  21658. var shapeRotation = this._colliderShape.localRotation;
  21659. var nativeRotation = PhysicsComponent._nativeQuaternion0;
  21660. if (shapeRotation.x !== 0 || shapeRotation.y !== 0 || shapeRotation.z !== 0 || shapeRotation.w !== 1) {
  21661. var physicRotation = PhysicsComponent._tempQuaternion0;
  21662. PhysicsComponent.physicQuaternionMultiply(rotation.x, rotation.y, rotation.z, rotation.w, shapeRotation, physicRotation);
  21663. nativeRotation.setValue(-physicRotation.x, physicRotation.y, physicRotation.z, -physicRotation.w);
  21664. }
  21665. else {
  21666. nativeRotation.setValue(-rotation.x, rotation.y, rotation.z, -rotation.w);
  21667. }
  21668. physicTransformOut.setRotation(nativeRotation);
  21669. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  21670. }
  21671. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  21672. this._onScaleChange(transform.getWorldLossyScale());
  21673. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  21674. }
  21675. }
  21676. _updateTransformComponent(physicsTransform) {
  21677. var localOffset = this._colliderShape.localOffset;
  21678. var localRotation = this._colliderShape.localRotation;
  21679. var transform = this.owner._transform;
  21680. var position = transform.position;
  21681. var rotation = transform.rotation;
  21682. var nativePosition = physicsTransform.getOrigin();
  21683. var nativeRotation = physicsTransform.getRotation();
  21684. var nativeRotX = -nativeRotation.x();
  21685. var nativeRotY = nativeRotation.y();
  21686. var nativeRotZ = nativeRotation.z();
  21687. var nativeRotW = -nativeRotation.w();
  21688. if (localOffset.x !== 0 || localOffset.y !== 0 || localOffset.z !== 0) {
  21689. var rotShapePosition = PhysicsComponent._tempVector30;
  21690. PhysicsComponent.physicVector3TransformQuat(localOffset, nativeRotX, nativeRotY, nativeRotZ, nativeRotW, rotShapePosition);
  21691. position.x = -nativePosition.x() - rotShapePosition.x;
  21692. position.y = nativePosition.y() - rotShapePosition.y;
  21693. position.z = nativePosition.z() - rotShapePosition.z;
  21694. }
  21695. else {
  21696. position.x = -nativePosition.x();
  21697. position.y = nativePosition.y();
  21698. position.z = nativePosition.z();
  21699. }
  21700. transform.position = position;
  21701. if (localRotation.x !== 0 || localRotation.y !== 0 || localRotation.z !== 0 || localRotation.w !== 1) {
  21702. var invertShapeRotaion = PhysicsComponent._tempQuaternion0;
  21703. localRotation.invert(invertShapeRotaion);
  21704. PhysicsComponent.physicQuaternionMultiply(nativeRotX, nativeRotY, nativeRotZ, nativeRotW, invertShapeRotaion, rotation);
  21705. }
  21706. else {
  21707. rotation.x = nativeRotX;
  21708. rotation.y = nativeRotY;
  21709. rotation.z = nativeRotZ;
  21710. rotation.w = nativeRotW;
  21711. }
  21712. transform.rotation = rotation;
  21713. }
  21714. _onEnable() {
  21715. this._simulation = this.owner._scene.physicsSimulation;
  21716. this._nativeColliderObject.setContactProcessingThreshold(1e30);
  21717. if (this._colliderShape && this._enabled) {
  21718. this._derivePhysicsTransformation(true);
  21719. this._addToSimulation();
  21720. }
  21721. }
  21722. _onDisable() {
  21723. if (this._colliderShape && this._enabled) {
  21724. this._removeFromSimulation();
  21725. (this._inPhysicUpdateListIndex !== -1) && (this._simulation._physicsUpdateList.remove(this));
  21726. }
  21727. this._simulation = null;
  21728. }
  21729. _onShapeChange(colShape) {
  21730. var btColObj = this._nativeColliderObject;
  21731. var flags = btColObj.getCollisionFlags();
  21732. if (colShape.needsCustomCollisionCallback) {
  21733. if ((flags & PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK) === 0)
  21734. btColObj.setCollisionFlags(flags | PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK);
  21735. }
  21736. else {
  21737. if ((flags & PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK) > 0)
  21738. btColObj.setCollisionFlags(flags ^ PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK);
  21739. }
  21740. }
  21741. _onAdded() {
  21742. this.enabled = this._enabled;
  21743. this.restitution = this._restitution;
  21744. this.friction = this._friction;
  21745. this.rollingFriction = this._rollingFriction;
  21746. this.ccdMotionThreshold = this._ccdMotionThreshold;
  21747. this.ccdSweptSphereRadius = this._ccdSweptSphereRadius;
  21748. this.owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  21749. }
  21750. _onDestroy() {
  21751. var physics3D = Physics3D._physics3D;
  21752. delete PhysicsComponent._physicObjectsMap[this.id];
  21753. physics3D.destroy(this._nativeColliderObject);
  21754. this._colliderShape.destroy();
  21755. super._onDestroy();
  21756. this._nativeColliderObject = null;
  21757. this._colliderShape = null;
  21758. this._simulation = null;
  21759. this.owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  21760. }
  21761. _onTransformChanged(flag) {
  21762. if (PhysicsComponent._addUpdateList) {
  21763. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  21764. if (flag) {
  21765. this._transformFlag |= flag;
  21766. if (this._isValid() && this._inPhysicUpdateListIndex === -1)
  21767. this._simulation._physicsUpdateList.add(this);
  21768. }
  21769. }
  21770. }
  21771. _cloneTo(dest) {
  21772. var destPhysicsComponent = dest;
  21773. destPhysicsComponent.restitution = this._restitution;
  21774. destPhysicsComponent.friction = this._friction;
  21775. destPhysicsComponent.rollingFriction = this._rollingFriction;
  21776. destPhysicsComponent.ccdMotionThreshold = this._ccdMotionThreshold;
  21777. destPhysicsComponent.ccdSweptSphereRadius = this._ccdSweptSphereRadius;
  21778. destPhysicsComponent.collisionGroup = this._collisionGroup;
  21779. destPhysicsComponent.canCollideWith = this._canCollideWith;
  21780. destPhysicsComponent.canScaleShape = this.canScaleShape;
  21781. (this._colliderShape) && (destPhysicsComponent.colliderShape = this._colliderShape.clone());
  21782. }
  21783. }
  21784. PhysicsComponent.ACTIVATIONSTATE_ACTIVE_TAG = 1;
  21785. PhysicsComponent.ACTIVATIONSTATE_ISLAND_SLEEPING = 2;
  21786. PhysicsComponent.ACTIVATIONSTATE_WANTS_DEACTIVATION = 3;
  21787. PhysicsComponent.ACTIVATIONSTATE_DISABLE_DEACTIVATION = 4;
  21788. PhysicsComponent.ACTIVATIONSTATE_DISABLE_SIMULATION = 5;
  21789. PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT = 1;
  21790. PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT = 2;
  21791. PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE = 4;
  21792. PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK = 8;
  21793. PhysicsComponent.COLLISIONFLAGS_CHARACTER_OBJECT = 16;
  21794. PhysicsComponent.COLLISIONFLAGS_DISABLE_VISUALIZE_OBJECT = 32;
  21795. PhysicsComponent.COLLISIONFLAGS_DISABLE_SPU_COLLISION_PROCESSING = 64;
  21796. PhysicsComponent._tempVector30 = new Vector3();
  21797. PhysicsComponent._tempQuaternion0 = new Quaternion();
  21798. PhysicsComponent._tempQuaternion1 = new Quaternion();
  21799. PhysicsComponent._tempMatrix4x40 = new Matrix4x4();
  21800. PhysicsComponent._physicObjectsMap = {};
  21801. PhysicsComponent._addUpdateList = true;
  21802. class PhysicsSimulation {
  21803. constructor(configuration, flags = 0) {
  21804. this._gravity = new Vector3(0, -10, 0);
  21805. this._nativeVector3Zero = new Physics3D._physics3D.btVector3(0, 0, 0);
  21806. this._nativeDefaultQuaternion = new Physics3D._physics3D.btQuaternion(0, 0, 0, -1);
  21807. this._collisionsUtils = new CollisionTool();
  21808. this._previousFrameCollisions = [];
  21809. this._currentFrameCollisions = [];
  21810. this._physicsUpdateList = new PhysicsUpdateList();
  21811. this._characters = [];
  21812. this._updatedRigidbodies = 0;
  21813. this.maxSubSteps = 1;
  21814. this.fixedTimeStep = 1.0 / 60.0;
  21815. this.maxSubSteps = configuration.maxSubSteps;
  21816. this.fixedTimeStep = configuration.fixedTimeStep;
  21817. var physics3D = Physics3D._physics3D;
  21818. this._nativeCollisionConfiguration = new physics3D.btDefaultCollisionConfiguration();
  21819. this._nativeDispatcher = new physics3D.btCollisionDispatcher(this._nativeCollisionConfiguration);
  21820. this._nativeBroadphase = new physics3D.btDbvtBroadphase();
  21821. this._nativeBroadphase.getOverlappingPairCache().setInternalGhostPairCallback(new physics3D.btGhostPairCallback());
  21822. var conFlags = configuration.flags;
  21823. if (conFlags & PhysicsSimulation.PHYSICSENGINEFLAGS_COLLISIONSONLY) {
  21824. this._nativeCollisionWorld = new physics3D.btCollisionWorld(this._nativeDispatcher, this._nativeBroadphase, this._nativeCollisionConfiguration);
  21825. }
  21826. else if (conFlags & PhysicsSimulation.PHYSICSENGINEFLAGS_SOFTBODYSUPPORT) {
  21827. throw "PhysicsSimulation:SoftBody processing is not yet available";
  21828. }
  21829. else {
  21830. var solver = new physics3D.btSequentialImpulseConstraintSolver();
  21831. this._nativeDiscreteDynamicsWorld = new physics3D.btDiscreteDynamicsWorld(this._nativeDispatcher, this._nativeBroadphase, solver, this._nativeCollisionConfiguration);
  21832. this._nativeCollisionWorld = this._nativeDiscreteDynamicsWorld;
  21833. }
  21834. if (this._nativeDiscreteDynamicsWorld) {
  21835. this._nativeSolverInfo = this._nativeDiscreteDynamicsWorld.getSolverInfo();
  21836. this._nativeDispatchInfo = this._nativeDiscreteDynamicsWorld.getDispatchInfo();
  21837. }
  21838. this._nativeClosestRayResultCallback = new physics3D.ClosestRayResultCallback(this._nativeVector3Zero, this._nativeVector3Zero);
  21839. this._nativeAllHitsRayResultCallback = new physics3D.AllHitsRayResultCallback(this._nativeVector3Zero, this._nativeVector3Zero);
  21840. this._nativeClosestConvexResultCallback = new physics3D.ClosestConvexResultCallback(this._nativeVector3Zero, this._nativeVector3Zero);
  21841. this._nativeAllConvexResultCallback = new physics3D.AllConvexResultCallback(this._nativeVector3Zero, this._nativeVector3Zero);
  21842. physics3D._btGImpactCollisionAlgorithm_RegisterAlgorithm(this._nativeDispatcher.a);
  21843. }
  21844. static __init__() {
  21845. PhysicsSimulation._nativeTempVector30 = new Physics3D._physics3D.btVector3(0, 0, 0);
  21846. PhysicsSimulation._nativeTempVector31 = new Physics3D._physics3D.btVector3(0, 0, 0);
  21847. PhysicsSimulation._nativeTempQuaternion0 = new Physics3D._physics3D.btQuaternion(0, 0, 0, 1);
  21848. PhysicsSimulation._nativeTempQuaternion1 = new Physics3D._physics3D.btQuaternion(0, 0, 0, 1);
  21849. PhysicsSimulation._nativeTempTransform0 = new Physics3D._physics3D.btTransform();
  21850. PhysicsSimulation._nativeTempTransform1 = new Physics3D._physics3D.btTransform();
  21851. }
  21852. static createConstraint() {
  21853. }
  21854. get continuousCollisionDetection() {
  21855. return this._nativeDispatchInfo.get_m_useContinuous();
  21856. }
  21857. set continuousCollisionDetection(value) {
  21858. this._nativeDispatchInfo.set_m_useContinuous(value);
  21859. }
  21860. get gravity() {
  21861. if (!this._nativeDiscreteDynamicsWorld)
  21862. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  21863. return this._gravity;
  21864. }
  21865. set gravity(value) {
  21866. if (!this._nativeDiscreteDynamicsWorld)
  21867. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  21868. this._gravity = value;
  21869. var nativeGravity = PhysicsSimulation._nativeTempVector30;
  21870. nativeGravity.setValue(-value.x, value.y, value.z);
  21871. this._nativeDiscreteDynamicsWorld.setGravity(nativeGravity);
  21872. }
  21873. get speculativeContactRestitution() {
  21874. if (!this._nativeDiscreteDynamicsWorld)
  21875. throw "Simulation:Cannot Cannot perform this action when the physics engine is set to CollisionsOnly";
  21876. return this._nativeDiscreteDynamicsWorld.getApplySpeculativeContactRestitution();
  21877. }
  21878. set speculativeContactRestitution(value) {
  21879. if (!this._nativeDiscreteDynamicsWorld)
  21880. throw "Simulation:Cannot Cannot perform this action when the physics engine is set to CollisionsOnly";
  21881. this._nativeDiscreteDynamicsWorld.setApplySpeculativeContactRestitution(value);
  21882. }
  21883. _simulate(deltaTime) {
  21884. this._updatedRigidbodies = 0;
  21885. if (this._nativeDiscreteDynamicsWorld)
  21886. this._nativeDiscreteDynamicsWorld.stepSimulation(deltaTime, this.maxSubSteps, this.fixedTimeStep);
  21887. else
  21888. this._nativeCollisionWorld.PerformDiscreteCollisionDetection();
  21889. }
  21890. _destroy() {
  21891. var physics3D = Physics3D._physics3D;
  21892. if (this._nativeDiscreteDynamicsWorld) {
  21893. physics3D.destroy(this._nativeDiscreteDynamicsWorld);
  21894. this._nativeDiscreteDynamicsWorld = null;
  21895. }
  21896. else {
  21897. physics3D.destroy(this._nativeCollisionWorld);
  21898. this._nativeCollisionWorld = null;
  21899. }
  21900. physics3D.destroy(this._nativeBroadphase);
  21901. this._nativeBroadphase = null;
  21902. physics3D.destroy(this._nativeDispatcher);
  21903. this._nativeDispatcher = null;
  21904. physics3D.destroy(this._nativeCollisionConfiguration);
  21905. this._nativeCollisionConfiguration = null;
  21906. }
  21907. _addPhysicsCollider(component, group, mask) {
  21908. this._nativeCollisionWorld.addCollisionObject(component._nativeColliderObject, group, mask);
  21909. }
  21910. _removePhysicsCollider(component) {
  21911. this._nativeCollisionWorld.removeCollisionObject(component._nativeColliderObject);
  21912. }
  21913. _addRigidBody(rigidBody, group, mask) {
  21914. if (!this._nativeDiscreteDynamicsWorld)
  21915. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  21916. this._nativeCollisionWorld.addRigidBody(rigidBody._nativeColliderObject, group, mask);
  21917. }
  21918. _removeRigidBody(rigidBody) {
  21919. if (!this._nativeDiscreteDynamicsWorld)
  21920. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  21921. this._nativeCollisionWorld.removeRigidBody(rigidBody._nativeColliderObject);
  21922. }
  21923. _addCharacter(character, group, mask) {
  21924. if (!this._nativeDiscreteDynamicsWorld)
  21925. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  21926. this._nativeCollisionWorld.addCollisionObject(character._nativeColliderObject, group, mask);
  21927. this._nativeCollisionWorld.addAction(character._nativeKinematicCharacter);
  21928. }
  21929. _removeCharacter(character) {
  21930. if (!this._nativeDiscreteDynamicsWorld)
  21931. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  21932. this._nativeCollisionWorld.removeCollisionObject(character._nativeColliderObject);
  21933. this._nativeCollisionWorld.removeAction(character._nativeKinematicCharacter);
  21934. }
  21935. raycastFromTo(from, to, out = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  21936. var rayResultCall = this._nativeClosestRayResultCallback;
  21937. var rayFrom = PhysicsSimulation._nativeTempVector30;
  21938. var rayTo = PhysicsSimulation._nativeTempVector31;
  21939. rayFrom.setValue(-from.x, from.y, from.z);
  21940. rayTo.setValue(-to.x, to.y, to.z);
  21941. rayResultCall.set_m_rayFromWorld(rayFrom);
  21942. rayResultCall.set_m_rayToWorld(rayTo);
  21943. rayResultCall.set_m_collisionFilterGroup(collisonGroup);
  21944. rayResultCall.set_m_collisionFilterMask(collisionMask);
  21945. rayResultCall.set_m_collisionObject(null);
  21946. rayResultCall.set_m_closestHitFraction(1);
  21947. this._nativeCollisionWorld.rayTest(rayFrom, rayTo, rayResultCall);
  21948. if (rayResultCall.hasHit()) {
  21949. if (out) {
  21950. out.succeeded = true;
  21951. out.collider = PhysicsComponent._physicObjectsMap[rayResultCall.get_m_collisionObject().getUserIndex()];
  21952. out.hitFraction = rayResultCall.get_m_closestHitFraction();
  21953. var nativePoint = rayResultCall.get_m_hitPointWorld();
  21954. var point = out.point;
  21955. point.x = -nativePoint.x();
  21956. point.y = nativePoint.y();
  21957. point.z = nativePoint.z();
  21958. var nativeNormal = rayResultCall.get_m_hitNormalWorld();
  21959. var normal = out.normal;
  21960. normal.x = -nativeNormal.x();
  21961. normal.y = nativeNormal.y();
  21962. normal.z = nativeNormal.z();
  21963. }
  21964. return true;
  21965. }
  21966. else {
  21967. if (out)
  21968. out.succeeded = false;
  21969. return false;
  21970. }
  21971. }
  21972. raycastAllFromTo(from, to, out, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  21973. var rayResultCall = this._nativeAllHitsRayResultCallback;
  21974. var rayFrom = PhysicsSimulation._nativeTempVector30;
  21975. var rayTo = PhysicsSimulation._nativeTempVector31;
  21976. out.length = 0;
  21977. rayFrom.setValue(-from.x, from.y, from.z);
  21978. rayTo.setValue(-to.x, to.y, to.z);
  21979. rayResultCall.set_m_rayFromWorld(rayFrom);
  21980. rayResultCall.set_m_rayToWorld(rayTo);
  21981. rayResultCall.set_m_collisionFilterGroup(collisonGroup);
  21982. rayResultCall.set_m_collisionFilterMask(collisionMask);
  21983. var collisionObjects = rayResultCall.get_m_collisionObjects();
  21984. var nativePoints = rayResultCall.get_m_hitPointWorld();
  21985. var nativeNormals = rayResultCall.get_m_hitNormalWorld();
  21986. var nativeFractions = rayResultCall.get_m_hitFractions();
  21987. collisionObjects.clear();
  21988. nativePoints.clear();
  21989. nativeNormals.clear();
  21990. nativeFractions.clear();
  21991. this._nativeCollisionWorld.rayTest(rayFrom, rayTo, rayResultCall);
  21992. var count = collisionObjects.size();
  21993. if (count > 0) {
  21994. this._collisionsUtils.recoverAllHitResultsPool();
  21995. for (var i = 0; i < count; i++) {
  21996. var hitResult = this._collisionsUtils.getHitResult();
  21997. out.push(hitResult);
  21998. hitResult.succeeded = true;
  21999. hitResult.collider = PhysicsComponent._physicObjectsMap[collisionObjects.at(i).getUserIndex()];
  22000. hitResult.hitFraction = nativeFractions.at(i);
  22001. var nativePoint = nativePoints.at(i);
  22002. var pointE = hitResult.point;
  22003. pointE.x = -nativePoint.x();
  22004. pointE.y = nativePoint.y();
  22005. pointE.z = nativePoint.z();
  22006. var nativeNormal = nativeNormals.at(i);
  22007. var normalE = hitResult.normal;
  22008. normalE.x = -nativeNormal.x();
  22009. normalE.y = nativeNormal.y();
  22010. normalE.z = nativeNormal.z();
  22011. }
  22012. return true;
  22013. }
  22014. else {
  22015. return false;
  22016. }
  22017. }
  22018. rayCast(ray, outHitResult = null, distance = 2147483647, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  22019. var from = ray.origin;
  22020. var to = PhysicsSimulation._tempVector30;
  22021. Vector3.normalize(ray.direction, to);
  22022. Vector3.scale(to, distance, to);
  22023. Vector3.add(from, to, to);
  22024. return this.raycastFromTo(from, to, outHitResult, collisonGroup, collisionMask);
  22025. }
  22026. rayCastAll(ray, out, distance = 2147483647, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  22027. var from = ray.origin;
  22028. var to = PhysicsSimulation._tempVector30;
  22029. Vector3.normalize(ray.direction, to);
  22030. Vector3.scale(to, distance, to);
  22031. Vector3.add(from, to, to);
  22032. return this.raycastAllFromTo(from, to, out, collisonGroup, collisionMask);
  22033. }
  22034. shapeCast(shape, fromPosition, toPosition, out = null, fromRotation = null, toRotation = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, allowedCcdPenetration = 0.0) {
  22035. var convexResultCall = this._nativeClosestConvexResultCallback;
  22036. var convexPosFrom = PhysicsSimulation._nativeTempVector30;
  22037. var convexPosTo = PhysicsSimulation._nativeTempVector31;
  22038. var convexRotFrom = PhysicsSimulation._nativeTempQuaternion0;
  22039. var convexRotTo = PhysicsSimulation._nativeTempQuaternion1;
  22040. var convexTransform = PhysicsSimulation._nativeTempTransform0;
  22041. var convexTransTo = PhysicsSimulation._nativeTempTransform1;
  22042. var sweepShape = shape._nativeShape;
  22043. convexPosFrom.setValue(-fromPosition.x, fromPosition.y, fromPosition.z);
  22044. convexPosTo.setValue(-toPosition.x, toPosition.y, toPosition.z);
  22045. convexResultCall.set_m_collisionFilterGroup(collisonGroup);
  22046. convexResultCall.set_m_collisionFilterMask(collisionMask);
  22047. convexTransform.setOrigin(convexPosFrom);
  22048. convexTransTo.setOrigin(convexPosTo);
  22049. if (fromRotation) {
  22050. convexRotFrom.setValue(-fromRotation.x, fromRotation.y, fromRotation.z, -fromRotation.w);
  22051. convexTransform.setRotation(convexRotFrom);
  22052. }
  22053. else {
  22054. convexTransform.setRotation(this._nativeDefaultQuaternion);
  22055. }
  22056. if (toRotation) {
  22057. convexRotTo.setValue(-toRotation.x, toRotation.y, toRotation.z, -toRotation.w);
  22058. convexTransTo.setRotation(convexRotTo);
  22059. }
  22060. else {
  22061. convexTransTo.setRotation(this._nativeDefaultQuaternion);
  22062. }
  22063. convexResultCall.set_m_hitCollisionObject(null);
  22064. convexResultCall.set_m_closestHitFraction(1);
  22065. this._nativeCollisionWorld.convexSweepTest(sweepShape, convexTransform, convexTransTo, convexResultCall, allowedCcdPenetration);
  22066. if (convexResultCall.hasHit()) {
  22067. if (out) {
  22068. out.succeeded = true;
  22069. out.collider = PhysicsComponent._physicObjectsMap[convexResultCall.get_m_hitCollisionObject().getUserIndex()];
  22070. out.hitFraction = convexResultCall.get_m_closestHitFraction();
  22071. var nativePoint = convexResultCall.get_m_hitPointWorld();
  22072. var nativeNormal = convexResultCall.get_m_hitNormalWorld();
  22073. var point = out.point;
  22074. var normal = out.normal;
  22075. point.x = -nativePoint.x();
  22076. point.y = nativePoint.y();
  22077. point.z = nativePoint.z();
  22078. normal.x = -nativeNormal.x();
  22079. normal.y = nativeNormal.y();
  22080. normal.z = nativeNormal.z();
  22081. }
  22082. return true;
  22083. }
  22084. else {
  22085. if (out)
  22086. out.succeeded = false;
  22087. return false;
  22088. }
  22089. }
  22090. shapeCastAll(shape, fromPosition, toPosition, out, fromRotation = null, toRotation = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, allowedCcdPenetration = 0.0) {
  22091. var convexResultCall = this._nativeAllConvexResultCallback;
  22092. var convexPosFrom = PhysicsSimulation._nativeTempVector30;
  22093. var convexPosTo = PhysicsSimulation._nativeTempVector31;
  22094. var convexRotFrom = PhysicsSimulation._nativeTempQuaternion0;
  22095. var convexRotTo = PhysicsSimulation._nativeTempQuaternion1;
  22096. var convexTransform = PhysicsSimulation._nativeTempTransform0;
  22097. var convexTransTo = PhysicsSimulation._nativeTempTransform1;
  22098. var sweepShape = shape._nativeShape;
  22099. out.length = 0;
  22100. convexPosFrom.setValue(-fromPosition.x, fromPosition.y, fromPosition.z);
  22101. convexPosTo.setValue(-toPosition.x, toPosition.y, toPosition.z);
  22102. convexResultCall.set_m_collisionFilterGroup(collisonGroup);
  22103. convexResultCall.set_m_collisionFilterMask(collisionMask);
  22104. convexTransform.setOrigin(convexPosFrom);
  22105. convexTransTo.setOrigin(convexPosTo);
  22106. if (fromRotation) {
  22107. convexRotFrom.setValue(-fromRotation.x, fromRotation.y, fromRotation.z, -fromRotation.w);
  22108. convexTransform.setRotation(convexRotFrom);
  22109. }
  22110. else {
  22111. convexTransform.setRotation(this._nativeDefaultQuaternion);
  22112. }
  22113. if (toRotation) {
  22114. convexRotTo.setValue(-toRotation.x, toRotation.y, toRotation.z, -toRotation.w);
  22115. convexTransTo.setRotation(convexRotTo);
  22116. }
  22117. else {
  22118. convexTransTo.setRotation(this._nativeDefaultQuaternion);
  22119. }
  22120. var collisionObjects = convexResultCall.get_m_collisionObjects();
  22121. collisionObjects.clear();
  22122. this._nativeCollisionWorld.convexSweepTest(sweepShape, convexTransform, convexTransTo, convexResultCall, allowedCcdPenetration);
  22123. var count = collisionObjects.size();
  22124. if (count > 0) {
  22125. var nativePoints = convexResultCall.get_m_hitPointWorld();
  22126. var nativeNormals = convexResultCall.get_m_hitNormalWorld();
  22127. var nativeFractions = convexResultCall.get_m_hitFractions();
  22128. for (var i = 0; i < count; i++) {
  22129. var hitResult = this._collisionsUtils.getHitResult();
  22130. out.push(hitResult);
  22131. hitResult.succeeded = true;
  22132. hitResult.collider = PhysicsComponent._physicObjectsMap[collisionObjects.at(i).getUserIndex()];
  22133. hitResult.hitFraction = nativeFractions.at(i);
  22134. var nativePoint = nativePoints.at(i);
  22135. var point = hitResult.point;
  22136. point.x = -nativePoint.x();
  22137. point.y = nativePoint.y();
  22138. point.z = nativePoint.z();
  22139. var nativeNormal = nativeNormals.at(i);
  22140. var normal = hitResult.normal;
  22141. normal.x = -nativeNormal.x();
  22142. normal.y = nativeNormal.y();
  22143. normal.z = nativeNormal.z();
  22144. }
  22145. return true;
  22146. }
  22147. else {
  22148. return false;
  22149. }
  22150. }
  22151. addConstraint(constraint, disableCollisionsBetweenLinkedBodies = false) {
  22152. if (!this._nativeDiscreteDynamicsWorld)
  22153. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  22154. this._nativeDiscreteDynamicsWorld.addConstraint(constraint._nativeConstraint, disableCollisionsBetweenLinkedBodies);
  22155. constraint._simulation = this;
  22156. }
  22157. removeConstraint(constraint) {
  22158. if (!this._nativeDiscreteDynamicsWorld)
  22159. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  22160. this._nativeDiscreteDynamicsWorld.removeConstraint(constraint._nativeConstraint);
  22161. }
  22162. _updatePhysicsTransformFromRender() {
  22163. var elements = this._physicsUpdateList.elements;
  22164. for (var i = 0, n = this._physicsUpdateList.length; i < n; i++) {
  22165. var physicCollider = elements[i];
  22166. physicCollider._derivePhysicsTransformation(false);
  22167. physicCollider._inPhysicUpdateListIndex = -1;
  22168. }
  22169. this._physicsUpdateList.length = 0;
  22170. }
  22171. _updateCharacters() {
  22172. for (var i = 0, n = this._characters.length; i < n; i++) {
  22173. var character = this._characters[i];
  22174. character._updateTransformComponent(character._nativeColliderObject.getWorldTransform());
  22175. }
  22176. }
  22177. _updateCollisions() {
  22178. this._collisionsUtils.recoverAllContactPointsPool();
  22179. var previous = this._currentFrameCollisions;
  22180. this._currentFrameCollisions = this._previousFrameCollisions;
  22181. this._currentFrameCollisions.length = 0;
  22182. this._previousFrameCollisions = previous;
  22183. var loopCount = Laya.Stat.loopCount;
  22184. var numManifolds = this._nativeDispatcher.getNumManifolds();
  22185. for (var i = 0; i < numManifolds; i++) {
  22186. var contactManifold = this._nativeDispatcher.getManifoldByIndexInternal(i);
  22187. var componentA = PhysicsComponent._physicObjectsMap[contactManifold.getBody0().getUserIndex()];
  22188. var componentB = PhysicsComponent._physicObjectsMap[contactManifold.getBody1().getUserIndex()];
  22189. var collision = null;
  22190. var isFirstCollision;
  22191. var contacts = null;
  22192. var isTrigger = componentA.isTrigger || componentB.isTrigger;
  22193. if (isTrigger && (componentA.owner._needProcessTriggers || componentB.owner._needProcessTriggers)) {
  22194. var numContacts = contactManifold.getNumContacts();
  22195. for (var j = 0; j < numContacts; j++) {
  22196. var pt = contactManifold.getContactPoint(j);
  22197. var distance = pt.getDistance();
  22198. if (distance <= 0) {
  22199. collision = this._collisionsUtils.getCollision(componentA, componentB);
  22200. contacts = collision.contacts;
  22201. isFirstCollision = collision._updateFrame !== loopCount;
  22202. if (isFirstCollision) {
  22203. collision._isTrigger = true;
  22204. contacts.length = 0;
  22205. }
  22206. break;
  22207. }
  22208. }
  22209. }
  22210. else if (componentA.owner._needProcessCollisions || componentB.owner._needProcessCollisions) {
  22211. if (componentA._enableProcessCollisions || componentB._enableProcessCollisions) {
  22212. numContacts = contactManifold.getNumContacts();
  22213. for (j = 0; j < numContacts; j++) {
  22214. pt = contactManifold.getContactPoint(j);
  22215. distance = pt.getDistance();
  22216. if (distance <= 0) {
  22217. var contactPoint = this._collisionsUtils.getContactPoints();
  22218. contactPoint.colliderA = componentA;
  22219. contactPoint.colliderB = componentB;
  22220. contactPoint.distance = distance;
  22221. var nativeNormal = pt.get_m_normalWorldOnB();
  22222. var normal = contactPoint.normal;
  22223. normal.x = -nativeNormal.x();
  22224. normal.y = nativeNormal.y();
  22225. normal.z = nativeNormal.z();
  22226. var nativePostionA = pt.get_m_positionWorldOnA();
  22227. var positionOnA = contactPoint.positionOnA;
  22228. positionOnA.x = -nativePostionA.x();
  22229. positionOnA.y = nativePostionA.y();
  22230. positionOnA.z = nativePostionA.z();
  22231. var nativePostionB = pt.get_m_positionWorldOnB();
  22232. var positionOnB = contactPoint.positionOnB;
  22233. positionOnB.x = -nativePostionB.x();
  22234. positionOnB.y = nativePostionB.y();
  22235. positionOnB.z = nativePostionB.z();
  22236. if (!collision) {
  22237. collision = this._collisionsUtils.getCollision(componentA, componentB);
  22238. contacts = collision.contacts;
  22239. isFirstCollision = collision._updateFrame !== loopCount;
  22240. if (isFirstCollision) {
  22241. collision._isTrigger = false;
  22242. contacts.length = 0;
  22243. }
  22244. }
  22245. contacts.push(contactPoint);
  22246. }
  22247. }
  22248. }
  22249. }
  22250. if (collision && isFirstCollision) {
  22251. this._currentFrameCollisions.push(collision);
  22252. collision._setUpdateFrame(loopCount);
  22253. }
  22254. }
  22255. }
  22256. _eventScripts() {
  22257. var loopCount = Laya.Stat.loopCount;
  22258. for (var i = 0, n = this._currentFrameCollisions.length; i < n; i++) {
  22259. var curFrameCol = this._currentFrameCollisions[i];
  22260. var colliderA = curFrameCol._colliderA;
  22261. var colliderB = curFrameCol._colliderB;
  22262. if (colliderA.destroyed || colliderB.destroyed)
  22263. continue;
  22264. if (loopCount - curFrameCol._lastUpdateFrame === 1) {
  22265. var ownerA = colliderA.owner;
  22266. var scriptsA = ownerA._scripts;
  22267. if (scriptsA) {
  22268. if (curFrameCol._isTrigger) {
  22269. if (ownerA._needProcessTriggers) {
  22270. for (var j = 0, m = scriptsA.length; j < m; j++)
  22271. scriptsA[j].onTriggerStay(colliderB);
  22272. }
  22273. }
  22274. else {
  22275. if (ownerA._needProcessCollisions) {
  22276. for (j = 0, m = scriptsA.length; j < m; j++) {
  22277. curFrameCol.other = colliderB;
  22278. scriptsA[j].onCollisionStay(curFrameCol);
  22279. }
  22280. }
  22281. }
  22282. }
  22283. var ownerB = colliderB.owner;
  22284. var scriptsB = ownerB._scripts;
  22285. if (scriptsB) {
  22286. if (curFrameCol._isTrigger) {
  22287. if (ownerB._needProcessTriggers) {
  22288. for (j = 0, m = scriptsB.length; j < m; j++)
  22289. scriptsB[j].onTriggerStay(colliderA);
  22290. }
  22291. }
  22292. else {
  22293. if (ownerB._needProcessCollisions) {
  22294. for (j = 0, m = scriptsB.length; j < m; j++) {
  22295. curFrameCol.other = colliderA;
  22296. scriptsB[j].onCollisionStay(curFrameCol);
  22297. }
  22298. }
  22299. }
  22300. }
  22301. }
  22302. else {
  22303. ownerA = colliderA.owner;
  22304. scriptsA = ownerA._scripts;
  22305. if (scriptsA) {
  22306. if (curFrameCol._isTrigger) {
  22307. if (ownerA._needProcessTriggers) {
  22308. for (j = 0, m = scriptsA.length; j < m; j++)
  22309. scriptsA[j].onTriggerEnter(colliderB);
  22310. }
  22311. }
  22312. else {
  22313. if (ownerA._needProcessCollisions) {
  22314. for (j = 0, m = scriptsA.length; j < m; j++) {
  22315. curFrameCol.other = colliderB;
  22316. scriptsA[j].onCollisionEnter(curFrameCol);
  22317. }
  22318. }
  22319. }
  22320. }
  22321. ownerB = colliderB.owner;
  22322. scriptsB = ownerB._scripts;
  22323. if (scriptsB) {
  22324. if (curFrameCol._isTrigger) {
  22325. if (ownerB._needProcessTriggers) {
  22326. for (j = 0, m = scriptsB.length; j < m; j++)
  22327. scriptsB[j].onTriggerEnter(colliderA);
  22328. }
  22329. }
  22330. else {
  22331. if (ownerB._needProcessCollisions) {
  22332. for (j = 0, m = scriptsB.length; j < m; j++) {
  22333. curFrameCol.other = colliderA;
  22334. scriptsB[j].onCollisionEnter(curFrameCol);
  22335. }
  22336. }
  22337. }
  22338. }
  22339. }
  22340. }
  22341. for (i = 0, n = this._previousFrameCollisions.length; i < n; i++) {
  22342. var preFrameCol = this._previousFrameCollisions[i];
  22343. var preColliderA = preFrameCol._colliderA;
  22344. var preColliderB = preFrameCol._colliderB;
  22345. if (preColliderA.destroyed || preColliderB.destroyed)
  22346. continue;
  22347. if (loopCount - preFrameCol._updateFrame === 1) {
  22348. this._collisionsUtils.recoverCollision(preFrameCol);
  22349. ownerA = preColliderA.owner;
  22350. scriptsA = ownerA._scripts;
  22351. if (scriptsA) {
  22352. if (preFrameCol._isTrigger) {
  22353. if (ownerA._needProcessTriggers) {
  22354. for (j = 0, m = scriptsA.length; j < m; j++)
  22355. scriptsA[j].onTriggerExit(preColliderB);
  22356. }
  22357. }
  22358. else {
  22359. if (ownerA._needProcessCollisions) {
  22360. for (j = 0, m = scriptsA.length; j < m; j++) {
  22361. preFrameCol.other = preColliderB;
  22362. scriptsA[j].onCollisionExit(preFrameCol);
  22363. }
  22364. }
  22365. }
  22366. }
  22367. ownerB = preColliderB.owner;
  22368. scriptsB = ownerB._scripts;
  22369. if (scriptsB) {
  22370. if (preFrameCol._isTrigger) {
  22371. if (ownerB._needProcessTriggers) {
  22372. for (j = 0, m = scriptsB.length; j < m; j++)
  22373. scriptsB[j].onTriggerExit(preColliderA);
  22374. }
  22375. }
  22376. else {
  22377. if (ownerB._needProcessCollisions) {
  22378. for (j = 0, m = scriptsB.length; j < m; j++) {
  22379. preFrameCol.other = preColliderA;
  22380. scriptsB[j].onCollisionExit(preFrameCol);
  22381. }
  22382. }
  22383. }
  22384. }
  22385. }
  22386. }
  22387. }
  22388. clearForces() {
  22389. if (!this._nativeDiscreteDynamicsWorld)
  22390. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  22391. this._nativeDiscreteDynamicsWorld.clearForces();
  22392. }
  22393. }
  22394. PhysicsSimulation.PHYSICSENGINEFLAGS_NONE = 0x0;
  22395. PhysicsSimulation.PHYSICSENGINEFLAGS_COLLISIONSONLY = 0x1;
  22396. PhysicsSimulation.PHYSICSENGINEFLAGS_SOFTBODYSUPPORT = 0x2;
  22397. PhysicsSimulation.PHYSICSENGINEFLAGS_MULTITHREADED = 0x4;
  22398. PhysicsSimulation.PHYSICSENGINEFLAGS_USEHARDWAREWHENPOSSIBLE = 0x8;
  22399. PhysicsSimulation.SOLVERMODE_RANDMIZE_ORDER = 1;
  22400. PhysicsSimulation.SOLVERMODE_FRICTION_SEPARATE = 2;
  22401. PhysicsSimulation.SOLVERMODE_USE_WARMSTARTING = 4;
  22402. PhysicsSimulation.SOLVERMODE_USE_2_FRICTION_DIRECTIONS = 16;
  22403. PhysicsSimulation.SOLVERMODE_ENABLE_FRICTION_DIRECTION_CACHING = 32;
  22404. PhysicsSimulation.SOLVERMODE_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION = 64;
  22405. PhysicsSimulation.SOLVERMODE_CACHE_FRIENDLY = 128;
  22406. PhysicsSimulation.SOLVERMODE_SIMD = 256;
  22407. PhysicsSimulation.SOLVERMODE_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS = 512;
  22408. PhysicsSimulation.SOLVERMODE_ALLOW_ZERO_LENGTH_FRICTION_DIRECTIONS = 1024;
  22409. PhysicsSimulation._tempVector30 = new Vector3();
  22410. PhysicsSimulation.disableSimulation = false;
  22411. class Input3D {
  22412. constructor() {
  22413. this._eventList = [];
  22414. this._mouseTouch = new MouseTouch();
  22415. this._touchPool = [];
  22416. this._touches = new SimpleSingletonList();
  22417. this._multiTouchEnabled = true;
  22418. this._pushEventList = ((e) => {
  22419. (e.cancelable) && (e.preventDefault());
  22420. this._eventList.push(e);
  22421. }).bind(this);
  22422. }
  22423. __init__(canvas, scene) {
  22424. this._scene = scene;
  22425. canvas.oncontextmenu = function (e) {
  22426. return false;
  22427. };
  22428. }
  22429. _onCanvasEvent(canvas) {
  22430. canvas.addEventListener('mousedown', this._pushEventList);
  22431. canvas.addEventListener('mouseup', this._pushEventList, true);
  22432. canvas.addEventListener('mousemove', this._pushEventList, true);
  22433. canvas.addEventListener("touchstart", this._pushEventList);
  22434. canvas.addEventListener("touchend", this._pushEventList, true);
  22435. canvas.addEventListener("touchmove", this._pushEventList, true);
  22436. canvas.addEventListener("touchcancel", this._pushEventList, true);
  22437. }
  22438. _offCanvasEvent(canvas) {
  22439. canvas.removeEventListener('mousedown', this._pushEventList);
  22440. canvas.removeEventListener('mouseup', this._pushEventList, true);
  22441. canvas.removeEventListener('mousemove', this._pushEventList, true);
  22442. canvas.removeEventListener("touchstart", this._pushEventList);
  22443. canvas.removeEventListener("touchend", this._pushEventList, true);
  22444. canvas.removeEventListener("touchmove", this._pushEventList, true);
  22445. canvas.removeEventListener("touchcancel", this._pushEventList, true);
  22446. this._eventList.length = 0;
  22447. this._touches.length = 0;
  22448. }
  22449. touchCount() {
  22450. return this._touches.length;
  22451. }
  22452. get multiTouchEnabled() {
  22453. return this._multiTouchEnabled;
  22454. }
  22455. set multiTouchEnabled(value) {
  22456. this._multiTouchEnabled = value;
  22457. }
  22458. _getTouch(touchID) {
  22459. var touch = this._touchPool[touchID];
  22460. if (!touch) {
  22461. touch = new Touch();
  22462. this._touchPool[touchID] = touch;
  22463. touch._identifier = touchID;
  22464. }
  22465. return touch;
  22466. }
  22467. _mouseTouchDown() {
  22468. var touch = this._mouseTouch;
  22469. var sprite = touch.sprite;
  22470. touch._pressedSprite = sprite;
  22471. touch._pressedLoopCount = Laya.Stat.loopCount;
  22472. if (sprite) {
  22473. var scripts = sprite._scripts;
  22474. if (scripts) {
  22475. for (var i = 0, n = scripts.length; i < n; i++)
  22476. scripts[i].onMouseDown();
  22477. }
  22478. }
  22479. }
  22480. _mouseTouchUp() {
  22481. var i, n;
  22482. var touch = this._mouseTouch;
  22483. var lastPressedSprite = touch._pressedSprite;
  22484. touch._pressedSprite = null;
  22485. touch._pressedLoopCount = -1;
  22486. var sprite = touch.sprite;
  22487. if (sprite) {
  22488. if (sprite === lastPressedSprite) {
  22489. var scripts = sprite._scripts;
  22490. if (scripts) {
  22491. for (i = 0, n = scripts.length; i < n; i++)
  22492. scripts[i].onMouseClick();
  22493. }
  22494. }
  22495. }
  22496. if (lastPressedSprite) {
  22497. var lastScripts = lastPressedSprite._scripts;
  22498. if (lastScripts) {
  22499. for (i = 0, n = lastScripts.length; i < n; i++)
  22500. lastScripts[i].onMouseUp();
  22501. }
  22502. }
  22503. }
  22504. _mouseTouchRayCast(cameras) {
  22505. var touchHitResult = Input3D._tempHitResult0;
  22506. var touchPos = Input3D._tempVector20;
  22507. var touchRay = Input3D._tempRay0;
  22508. touchHitResult.succeeded = false;
  22509. var x = this._mouseTouch.mousePositionX;
  22510. var y = this._mouseTouch.mousePositionY;
  22511. touchPos.x = x;
  22512. touchPos.y = y;
  22513. for (var i = cameras.length - 1; i >= 0; i--) {
  22514. var camera = cameras[i];
  22515. var viewport = camera.viewport;
  22516. if (touchPos.x >= viewport.x && touchPos.y >= viewport.y && touchPos.x <= viewport.width && touchPos.y <= viewport.height) {
  22517. camera.viewportPointToRay(touchPos, touchRay);
  22518. var sucess = this._scene._physicsSimulation.rayCast(touchRay, touchHitResult);
  22519. if (sucess || (camera.clearFlag === BaseCamera.CLEARFLAG_SOLIDCOLOR || camera.clearFlag === BaseCamera.CLEARFLAG_SKY))
  22520. break;
  22521. }
  22522. }
  22523. var touch = this._mouseTouch;
  22524. var lastSprite = touch.sprite;
  22525. if (touchHitResult.succeeded) {
  22526. var touchSprite = touchHitResult.collider.owner;
  22527. touch.sprite = touchSprite;
  22528. var scripts = touchSprite._scripts;
  22529. if (lastSprite !== touchSprite) {
  22530. if (scripts) {
  22531. for (var j = 0, m = scripts.length; j < m; j++)
  22532. scripts[j].onMouseEnter();
  22533. }
  22534. }
  22535. }
  22536. else {
  22537. touch.sprite = null;
  22538. }
  22539. if (lastSprite && (lastSprite !== touchSprite)) {
  22540. var outScripts = lastSprite._scripts;
  22541. if (outScripts) {
  22542. for (j = 0, m = outScripts.length; j < m; j++)
  22543. outScripts[j].onMouseOut();
  22544. }
  22545. }
  22546. }
  22547. _changeTouches(changedTouches, flag) {
  22548. var offsetX = 0, offsetY = 0;
  22549. var lastCount = this._touches.length;
  22550. for (var j = 0, m = changedTouches.length; j < m; j++) {
  22551. var nativeTouch = changedTouches[j];
  22552. var identifier = nativeTouch.identifier;
  22553. if (!this._multiTouchEnabled && identifier !== 0)
  22554. continue;
  22555. var touch = this._getTouch(identifier);
  22556. var pos = touch._position;
  22557. var mousePoint = Input3D._tempPoint;
  22558. mousePoint.setTo(nativeTouch.pageX, nativeTouch.pageY);
  22559. Laya.ILaya.stage._canvasTransform.invertTransformPoint(mousePoint);
  22560. var posX = mousePoint.x;
  22561. var posY = mousePoint.y;
  22562. switch (flag) {
  22563. case 0:
  22564. this._touches.add(touch);
  22565. offsetX += posX;
  22566. offsetY += posY;
  22567. break;
  22568. case 1:
  22569. this._touches.remove(touch);
  22570. offsetX -= posX;
  22571. offsetY -= posY;
  22572. break;
  22573. case 2:
  22574. offsetX = posX - pos.x;
  22575. offsetY = posY - pos.y;
  22576. break;
  22577. }
  22578. pos.x = posX;
  22579. pos.y = posY;
  22580. }
  22581. var touchCount = this._touches.length;
  22582. if (touchCount === 0) {
  22583. this._mouseTouch.mousePositionX = 0;
  22584. this._mouseTouch.mousePositionY = 0;
  22585. }
  22586. else {
  22587. this._mouseTouch.mousePositionX = (this._mouseTouch.mousePositionX * lastCount + offsetX) / touchCount;
  22588. this._mouseTouch.mousePositionY = (this._mouseTouch.mousePositionY * lastCount + offsetY) / touchCount;
  22589. }
  22590. }
  22591. _update() {
  22592. var enablePhysics = Physics3D._enbalePhysics && !PhysicsSimulation.disableSimulation;
  22593. var i, n, j, m;
  22594. n = this._eventList.length;
  22595. var cameras = this._scene._cameraPool;
  22596. if (n > 0) {
  22597. var rayCast = false;
  22598. for (i = 0; i < n; i++) {
  22599. var e = this._eventList[i];
  22600. switch (e.type) {
  22601. case "mousedown":
  22602. (enablePhysics) && (this._mouseTouchDown());
  22603. break;
  22604. case "mouseup":
  22605. (enablePhysics) && (this._mouseTouchUp());
  22606. break;
  22607. case "mousemove":
  22608. var mousePoint = Input3D._tempPoint;
  22609. mousePoint.setTo(e.pageX, e.pageY);
  22610. Laya.ILaya.stage._canvasTransform.invertTransformPoint(mousePoint);
  22611. this._mouseTouch.mousePositionX = mousePoint.x;
  22612. this._mouseTouch.mousePositionY = mousePoint.y;
  22613. (enablePhysics) && (rayCast = true);
  22614. break;
  22615. case "touchstart":
  22616. var lastLength = this._touches.length;
  22617. this._changeTouches(e.changedTouches, 0);
  22618. if (enablePhysics) {
  22619. rayCast = true;
  22620. (lastLength === 0) && (this._mouseTouchDown());
  22621. }
  22622. break;
  22623. case "touchend":
  22624. case "touchcancel":
  22625. this._changeTouches(e.changedTouches, 1);
  22626. (enablePhysics && this._touches.length === 0) && (this._mouseTouchUp());
  22627. break;
  22628. case "touchmove":
  22629. this._changeTouches(e.changedTouches, 2);
  22630. (enablePhysics) && (rayCast = true);
  22631. break;
  22632. default:
  22633. throw "Input3D:unkonwn event type.";
  22634. }
  22635. }
  22636. (rayCast) && (this._mouseTouchRayCast(cameras));
  22637. this._eventList.length = 0;
  22638. }
  22639. if (enablePhysics) {
  22640. var mouseTouch = this._mouseTouch;
  22641. var pressedSprite = mouseTouch._pressedSprite;
  22642. if (pressedSprite && (Laya.Stat.loopCount > mouseTouch._pressedLoopCount)) {
  22643. var pressedScripts = pressedSprite._scripts;
  22644. if (pressedScripts) {
  22645. for (j = 0, m = pressedScripts.length; j < m; j++)
  22646. pressedScripts[j].onMouseDrag();
  22647. }
  22648. }
  22649. var touchSprite = mouseTouch.sprite;
  22650. if (touchSprite) {
  22651. var scripts = touchSprite._scripts;
  22652. if (scripts) {
  22653. for (j = 0, m = scripts.length; j < m; j++)
  22654. scripts[j].onMouseOver();
  22655. }
  22656. }
  22657. }
  22658. }
  22659. getTouch(index) {
  22660. if (index < this._touches.length) {
  22661. return this._touches.elements[index];
  22662. }
  22663. else {
  22664. return null;
  22665. }
  22666. }
  22667. }
  22668. Input3D._tempPoint = new Laya.Point();
  22669. Input3D._tempVector20 = new Vector2();
  22670. Input3D._tempRay0 = new Ray(new Vector3(), new Vector3());
  22671. Input3D._tempHitResult0 = new HitResult();
  22672. class PhysicsSettings {
  22673. constructor() {
  22674. this.flags = 0;
  22675. this.maxSubSteps = 1;
  22676. this.fixedTimeStep = 1.0 / 60.0;
  22677. }
  22678. }
  22679. class VertexPositionTexture0 {
  22680. static get vertexDeclaration() {
  22681. return VertexPositionTexture0._vertexDeclaration;
  22682. }
  22683. static __init__() {
  22684. VertexPositionTexture0._vertexDeclaration = new VertexDeclaration(20, [new VertexElement(0, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0),
  22685. new VertexElement(12, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE0)]);
  22686. }
  22687. get position() {
  22688. return this._position;
  22689. }
  22690. get textureCoordinate0() {
  22691. return this._textureCoordinate0;
  22692. }
  22693. get vertexDeclaration() {
  22694. return VertexPositionTexture0._vertexDeclaration;
  22695. }
  22696. constructor(position, textureCoordinate0) {
  22697. this._position = position;
  22698. this._textureCoordinate0 = textureCoordinate0;
  22699. }
  22700. }
  22701. class SkyDome extends SkyMesh {
  22702. constructor(stacks = 48, slices = 48) {
  22703. super();
  22704. var gl = Laya.LayaGL.instance;
  22705. this._stacks = stacks;
  22706. this._slices = slices;
  22707. var vertexDeclaration = VertexPositionTexture0.vertexDeclaration;
  22708. var vertexFloatCount = vertexDeclaration.vertexStride / 4;
  22709. var numberVertices = (this._stacks + 1) * (this._slices + 1);
  22710. var numberIndices = (3 * this._stacks * (this._slices + 1)) * 2;
  22711. var vertices = new Float32Array(numberVertices * vertexFloatCount);
  22712. var indices = new Uint16Array(numberIndices);
  22713. var stackAngle = Math.PI / this._stacks;
  22714. var sliceAngle = (Math.PI * 2.0) / this._slices;
  22715. var vertexIndex = 0;
  22716. var vertexCount = 0;
  22717. var indexCount = 0;
  22718. for (var stack = 0; stack < (this._stacks + 1); stack++) {
  22719. var r = Math.sin(stack * stackAngle);
  22720. var y = Math.cos(stack * stackAngle);
  22721. for (var slice = 0; slice < (this._slices + 1); slice++) {
  22722. var x = r * Math.sin(slice * sliceAngle);
  22723. var z = r * Math.cos(slice * sliceAngle);
  22724. vertices[vertexCount + 0] = x * SkyDome._radius;
  22725. vertices[vertexCount + 1] = y * SkyDome._radius;
  22726. vertices[vertexCount + 2] = z * SkyDome._radius;
  22727. vertices[vertexCount + 3] = -(slice / this._slices) + 0.75;
  22728. vertices[vertexCount + 4] = stack / this._stacks;
  22729. vertexCount += vertexFloatCount;
  22730. if (stack != (this._stacks - 1)) {
  22731. indices[indexCount++] = vertexIndex + 1;
  22732. indices[indexCount++] = vertexIndex;
  22733. indices[indexCount++] = vertexIndex + (this._slices + 1);
  22734. indices[indexCount++] = vertexIndex + (this._slices + 1);
  22735. indices[indexCount++] = vertexIndex;
  22736. indices[indexCount++] = vertexIndex + (this._slices);
  22737. vertexIndex++;
  22738. }
  22739. }
  22740. }
  22741. this._vertexBuffer = new VertexBuffer3D(vertices.length * 4, gl.STATIC_DRAW, false);
  22742. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  22743. this._indexBuffer = new IndexBuffer3D(IndexBuffer3D.INDEXTYPE_USHORT, indices.length, gl.STATIC_DRAW, false);
  22744. this._vertexBuffer.setData(vertices.buffer);
  22745. this._indexBuffer.setData(indices);
  22746. var bufferState = new BufferState();
  22747. bufferState.bind();
  22748. bufferState.applyVertexBuffer(this._vertexBuffer);
  22749. bufferState.applyIndexBuffer(this._indexBuffer);
  22750. bufferState.unBind();
  22751. this._bufferState = bufferState;
  22752. }
  22753. static __init__() {
  22754. SkyDome.instance = new SkyDome();
  22755. }
  22756. get stacks() {
  22757. return this._stacks;
  22758. }
  22759. get slices() {
  22760. return this._slices;
  22761. }
  22762. _render(state) {
  22763. var gl = Laya.LayaGL.instance;
  22764. var indexCount = this._indexBuffer.indexCount;
  22765. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  22766. Laya.Stat.trianglesFaces += indexCount / 3;
  22767. Laya.Stat.renderBatches++;
  22768. }
  22769. }
  22770. SkyDome._radius = 1;
  22771. class LightQueue {
  22772. constructor() {
  22773. this._length = 0;
  22774. this._elements = [];
  22775. }
  22776. add(light) {
  22777. if (this._length === this._elements.length)
  22778. this._elements.push(light);
  22779. else
  22780. this._elements[this._length] = light;
  22781. this._length++;
  22782. }
  22783. remove(light) {
  22784. var index = this._elements.indexOf(light);
  22785. this._length--;
  22786. if (index !== this._length) {
  22787. var end = this._elements[this._length];
  22788. this._elements[index] = end;
  22789. }
  22790. }
  22791. shift() {
  22792. this._length--;
  22793. return this._elements.shift();
  22794. }
  22795. }
  22796. class DirectionLightQueue extends LightQueue {
  22797. getSunLight() {
  22798. var maxIntIndex;
  22799. var maxIntensity = -1;
  22800. var elements = this._elements;
  22801. for (var i = 0; i < this._length; i++) {
  22802. var intensity = elements[i]._intensity;
  22803. if (maxIntensity < intensity) {
  22804. maxIntensity = intensity;
  22805. maxIntIndex = i;
  22806. }
  22807. }
  22808. return maxIntIndex;
  22809. }
  22810. }
  22811. class AlternateLightQueue extends LightQueue {
  22812. remove(light) {
  22813. var index = this._elements.indexOf(light);
  22814. this._elements.splice(index, 1);
  22815. this._length--;
  22816. }
  22817. }
  22818. class PixelLineFilter extends GeometryElement {
  22819. constructor(owner, maxLineCount) {
  22820. super();
  22821. this._floatCountPerVertices = 7;
  22822. this._minUpdate = Number.MAX_VALUE;
  22823. this._maxUpdate = Number.MIN_VALUE;
  22824. this._bufferState = new BufferState();
  22825. this._floatBound = new Float32Array(6);
  22826. this._calculateBound = false;
  22827. this._maxLineCount = 0;
  22828. this._lineCount = 0;
  22829. var pointCount = maxLineCount * 2;
  22830. this._owner = owner;
  22831. this._maxLineCount = maxLineCount;
  22832. this._vertices = new Float32Array(pointCount * this._floatCountPerVertices);
  22833. this._vertexBuffer = new VertexBuffer3D(PixelLineVertex.vertexDeclaration.vertexStride * pointCount, Laya.LayaGL.instance.STATIC_DRAW, false);
  22834. this._vertexBuffer.vertexDeclaration = PixelLineVertex.vertexDeclaration;
  22835. this._bufferState.bind();
  22836. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  22837. this._bufferState.unBind();
  22838. var min = PixelLineFilter._tempVector0;
  22839. var max = PixelLineFilter._tempVector1;
  22840. min.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22841. max.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22842. this._bounds = new Bounds(min, max);
  22843. }
  22844. _getType() {
  22845. return PixelLineFilter._type;
  22846. }
  22847. _resizeLineData(maxCount) {
  22848. var pointCount = maxCount * 2;
  22849. var lastVertices = this._vertices;
  22850. this._vertexBuffer.destroy();
  22851. this._maxLineCount = maxCount;
  22852. var vertexCount = pointCount * this._floatCountPerVertices;
  22853. this._vertices = new Float32Array(vertexCount);
  22854. this._vertexBuffer = new VertexBuffer3D(PixelLineVertex.vertexDeclaration.vertexStride * pointCount, Laya.LayaGL.instance.STATIC_DRAW, false);
  22855. this._vertexBuffer.vertexDeclaration = PixelLineVertex.vertexDeclaration;
  22856. if (vertexCount < lastVertices.length) {
  22857. this._vertices.set(new Float32Array(lastVertices.buffer, 0, vertexCount));
  22858. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, vertexCount * 4);
  22859. }
  22860. else {
  22861. this._vertices.set(lastVertices);
  22862. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, lastVertices.length * 4);
  22863. }
  22864. this._bufferState.bind();
  22865. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  22866. this._bufferState.unBind();
  22867. }
  22868. _updateLineVertices(offset, startPosition, endPosition, startColor, endColor) {
  22869. if (startPosition) {
  22870. this._vertices[offset + 0] = startPosition.x;
  22871. this._vertices[offset + 1] = startPosition.y;
  22872. this._vertices[offset + 2] = startPosition.z;
  22873. }
  22874. if (startColor) {
  22875. this._vertices[offset + 3] = startColor.r;
  22876. this._vertices[offset + 4] = startColor.g;
  22877. this._vertices[offset + 5] = startColor.b;
  22878. this._vertices[offset + 6] = startColor.a;
  22879. }
  22880. if (endPosition) {
  22881. this._vertices[offset + 7] = endPosition.x;
  22882. this._vertices[offset + 8] = endPosition.y;
  22883. this._vertices[offset + 9] = endPosition.z;
  22884. }
  22885. if (endColor) {
  22886. this._vertices[offset + 10] = endColor.r;
  22887. this._vertices[offset + 11] = endColor.g;
  22888. this._vertices[offset + 12] = endColor.b;
  22889. this._vertices[offset + 13] = endColor.a;
  22890. }
  22891. this._minUpdate = Math.min(this._minUpdate, offset);
  22892. this._maxUpdate = Math.max(this._maxUpdate, offset + this._floatCountPerVertices * 2);
  22893. var bounds = this._bounds;
  22894. var floatBound = this._floatBound;
  22895. var min = bounds.getMin(), max = bounds.getMax();
  22896. Vector3.min(min, startPosition, min);
  22897. Vector3.min(min, endPosition, min);
  22898. Vector3.max(max, startPosition, max);
  22899. Vector3.max(max, endPosition, max);
  22900. bounds.setMin(min);
  22901. bounds.setMax(max);
  22902. floatBound[0] = min.x, floatBound[1] = min.y, floatBound[2] = min.z;
  22903. floatBound[3] = max.x, floatBound[4] = max.y, floatBound[5] = max.z;
  22904. }
  22905. _reCalculateBound() {
  22906. if (this._calculateBound) {
  22907. var vertices = this._vertices;
  22908. var min = PixelLineFilter._tempVector0;
  22909. var max = PixelLineFilter._tempVector1;
  22910. min.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22911. max.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22912. for (var i = 0; i < this._lineCount * 2; ++i) {
  22913. var offset = this._floatCountPerVertices * i;
  22914. var x = vertices[offset + 0], y = vertices[offset + 1], z = vertices[offset + 2];
  22915. min.x = Math.min(x, min.x);
  22916. min.y = Math.min(y, min.y);
  22917. min.z = Math.min(z, min.z);
  22918. max.x = Math.max(x, max.x);
  22919. max.y = Math.max(y, max.y);
  22920. max.z = Math.max(z, max.z);
  22921. }
  22922. this._bounds.setMin(min);
  22923. this._bounds.setMax(max);
  22924. var floatBound = this._floatBound;
  22925. floatBound[0] = min.x, floatBound[1] = min.y, floatBound[2] = min.z;
  22926. floatBound[3] = max.x, floatBound[4] = max.y, floatBound[5] = max.z;
  22927. this._calculateBound = false;
  22928. }
  22929. }
  22930. _removeLineData(index) {
  22931. var floatCount = this._floatCountPerVertices * 2;
  22932. var nextIndex = index + 1;
  22933. var offset = index * floatCount;
  22934. var vertices = this._vertices;
  22935. var rightPartVertices = new Float32Array(vertices.buffer, nextIndex * floatCount * 4, (this._lineCount - nextIndex) * floatCount);
  22936. vertices.set(rightPartVertices, offset);
  22937. this._minUpdate = Math.min(this._minUpdate, offset);
  22938. this._maxUpdate = Math.max(this._maxUpdate, offset + rightPartVertices.length);
  22939. this._lineCount--;
  22940. var floatBound = this._floatBound;
  22941. var startX = vertices[offset], startY = vertices[offset + 1], startZ = vertices[offset + 2];
  22942. var endX = vertices[offset + 7], endY = vertices[offset + 8], endZ = vertices[offset + 9];
  22943. var minX = floatBound[0], minY = floatBound[1], minZ = floatBound[2];
  22944. var maxX = floatBound[3], maxY = floatBound[4], maxZ = floatBound[5];
  22945. if ((startX === minX) || (startX === maxX) || (startY === minY) || (startY === maxY) || (startZ === minZ) || (startZ === maxZ) ||
  22946. (endX === minX) || (endX === maxX) || (endY === minY) || (endY === maxY) || (endZ === minZ) || (endZ === maxZ))
  22947. this._calculateBound = true;
  22948. }
  22949. _updateLineData(index, startPosition, endPosition, startColor, endColor) {
  22950. var floatCount = this._floatCountPerVertices * 2;
  22951. this._updateLineVertices(index * floatCount, startPosition, endPosition, startColor, endColor);
  22952. }
  22953. _updateLineDatas(index, data) {
  22954. var floatCount = this._floatCountPerVertices * 2;
  22955. var count = data.length;
  22956. for (var i = 0; i < count; i++) {
  22957. var line = data[i];
  22958. this._updateLineVertices((index + i) * floatCount, line.startPosition, line.endPosition, line.startColor, line.endColor);
  22959. }
  22960. }
  22961. _getLineData(index, out) {
  22962. var startPosition = out.startPosition;
  22963. var startColor = out.startColor;
  22964. var endPosition = out.endPosition;
  22965. var endColor = out.endColor;
  22966. var vertices = this._vertices;
  22967. var offset = index * this._floatCountPerVertices * 2;
  22968. startPosition.x = vertices[offset + 0];
  22969. startPosition.y = vertices[offset + 1];
  22970. startPosition.z = vertices[offset + 2];
  22971. startColor.r = vertices[offset + 3];
  22972. startColor.g = vertices[offset + 4];
  22973. startColor.b = vertices[offset + 5];
  22974. startColor.a = vertices[offset + 6];
  22975. endPosition.x = vertices[offset + 7];
  22976. endPosition.y = vertices[offset + 8];
  22977. endPosition.z = vertices[offset + 9];
  22978. endColor.r = vertices[offset + 10];
  22979. endColor.g = vertices[offset + 11];
  22980. endColor.b = vertices[offset + 12];
  22981. endColor.a = vertices[offset + 13];
  22982. }
  22983. _prepareRender(state) {
  22984. return true;
  22985. }
  22986. _render(state) {
  22987. if (this._minUpdate !== Number.MAX_VALUE && this._maxUpdate !== Number.MIN_VALUE) {
  22988. this._vertexBuffer.setData(this._vertices.buffer, this._minUpdate * 4, this._minUpdate * 4, (this._maxUpdate - this._minUpdate) * 4);
  22989. this._minUpdate = Number.MAX_VALUE;
  22990. this._maxUpdate = Number.MIN_VALUE;
  22991. }
  22992. if (this._lineCount > 0) {
  22993. this._bufferState.bind();
  22994. var gl = Laya.LayaGL.instance;
  22995. gl.drawArrays(gl.LINES, 0, this._lineCount * 2);
  22996. Laya.Stat.renderBatches++;
  22997. }
  22998. }
  22999. destroy() {
  23000. if (this._destroyed)
  23001. return;
  23002. super.destroy();
  23003. this._bufferState.destroy();
  23004. this._vertexBuffer.destroy();
  23005. this._bufferState = null;
  23006. this._vertexBuffer = null;
  23007. this._vertices = null;
  23008. }
  23009. }
  23010. PixelLineFilter._tempVector0 = new Vector3();
  23011. PixelLineFilter._tempVector1 = new Vector3();
  23012. PixelLineFilter._type = GeometryElement._typeCounter++;
  23013. class PixelLineRenderer extends BaseRender {
  23014. constructor(owner) {
  23015. super(owner);
  23016. this._projectionViewWorldMatrix = new Matrix4x4();
  23017. }
  23018. _calculateBoundingBox() {
  23019. var worldMat = this._owner.transform.worldMatrix;
  23020. var lineFilter = this._owner._geometryFilter;
  23021. lineFilter._reCalculateBound();
  23022. lineFilter._bounds._tranform(worldMat, this._bounds);
  23023. if (Laya.Render.supportWebGLPlusCulling) {
  23024. var min = this._bounds.getMin();
  23025. var max = this._bounds.getMax();
  23026. var buffer = FrustumCulling._cullingBuffer;
  23027. buffer[this._cullingBufferIndex + 1] = min.x;
  23028. buffer[this._cullingBufferIndex + 2] = min.y;
  23029. buffer[this._cullingBufferIndex + 3] = min.z;
  23030. buffer[this._cullingBufferIndex + 4] = max.x;
  23031. buffer[this._cullingBufferIndex + 5] = max.y;
  23032. buffer[this._cullingBufferIndex + 6] = max.z;
  23033. }
  23034. }
  23035. _renderUpdateWithCamera(context, transform) {
  23036. var projectionView = context.projectionViewMatrix;
  23037. var sv = this._shaderValues;
  23038. if (transform) {
  23039. var worldMat = transform.worldMatrix;
  23040. sv.setMatrix4x4(Sprite3D.WORLDMATRIX, worldMat);
  23041. Matrix4x4.multiply(projectionView, worldMat, this._projectionViewWorldMatrix);
  23042. sv.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  23043. }
  23044. else {
  23045. sv.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  23046. sv.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  23047. }
  23048. }
  23049. }
  23050. class PixelLineSprite3D extends RenderableSprite3D {
  23051. get maxLineCount() {
  23052. return this._geometryFilter._maxLineCount;
  23053. }
  23054. set maxLineCount(value) {
  23055. this._geometryFilter._resizeLineData(value);
  23056. this._geometryFilter._lineCount = Math.min(this._geometryFilter._lineCount, value);
  23057. }
  23058. get lineCount() {
  23059. return this._geometryFilter._lineCount;
  23060. }
  23061. set lineCount(value) {
  23062. if (value > this.maxLineCount)
  23063. throw "PixelLineSprite3D: lineCount can't large than maxLineCount";
  23064. else
  23065. this._geometryFilter._lineCount = value;
  23066. }
  23067. get pixelLineRenderer() {
  23068. return this._render;
  23069. }
  23070. constructor(maxCount = 2, name = null) {
  23071. super(name);
  23072. this._geometryFilter = new PixelLineFilter(this, maxCount);
  23073. this._render = new PixelLineRenderer(this);
  23074. this._changeRenderObjects(this._render, 0, PixelLineMaterial.defaultMaterial);
  23075. }
  23076. _changeRenderObjects(sender, index, material) {
  23077. var renderObjects = this._render._renderElements;
  23078. (material) || (material = PixelLineMaterial.defaultMaterial);
  23079. var renderElement = renderObjects[index];
  23080. (renderElement) || (renderElement = renderObjects[index] = new RenderElement());
  23081. renderElement.setTransform(this._transform);
  23082. renderElement.setGeometry(this._geometryFilter);
  23083. renderElement.render = this._render;
  23084. renderElement.material = material;
  23085. }
  23086. addLine(startPosition, endPosition, startColor, endColor) {
  23087. if (this._geometryFilter._lineCount !== this._geometryFilter._maxLineCount)
  23088. this._geometryFilter._updateLineData(this._geometryFilter._lineCount++, startPosition, endPosition, startColor, endColor);
  23089. else
  23090. throw "PixelLineSprite3D: lineCount has equal with maxLineCount.";
  23091. }
  23092. addLines(lines) {
  23093. var lineCount = this._geometryFilter._lineCount;
  23094. var addCount = lines.length;
  23095. if (lineCount + addCount > this._geometryFilter._maxLineCount) {
  23096. throw "PixelLineSprite3D: lineCount plus lines count must less than maxLineCount.";
  23097. }
  23098. else {
  23099. this._geometryFilter._updateLineDatas(lineCount, lines);
  23100. this._geometryFilter._lineCount += addCount;
  23101. }
  23102. }
  23103. removeLine(index) {
  23104. if (index < this._geometryFilter._lineCount)
  23105. this._geometryFilter._removeLineData(index);
  23106. else
  23107. throw "PixelLineSprite3D: index must less than lineCount.";
  23108. }
  23109. setLine(index, startPosition, endPosition, startColor, endColor) {
  23110. if (index < this._geometryFilter._lineCount)
  23111. this._geometryFilter._updateLineData(index, startPosition, endPosition, startColor, endColor);
  23112. else
  23113. throw "PixelLineSprite3D: index must less than lineCount.";
  23114. }
  23115. getLine(index, out) {
  23116. if (index < this.lineCount)
  23117. this._geometryFilter._getLineData(index, out);
  23118. else
  23119. throw "PixelLineSprite3D: index must less than lineCount.";
  23120. }
  23121. clear() {
  23122. this._geometryFilter._lineCount = 0;
  23123. }
  23124. _create() {
  23125. return new PixelLineSprite3D();
  23126. }
  23127. }
  23128. class RenderQueue {
  23129. constructor(isTransparent = false) {
  23130. this.isTransparent = false;
  23131. this.elements = new SingletonList();
  23132. this.lastTransparentRenderElement = null;
  23133. this.lastTransparentBatched = false;
  23134. this.isTransparent = isTransparent;
  23135. }
  23136. _compare(left, right) {
  23137. var renderQueue = left.material.renderQueue - right.material.renderQueue;
  23138. if (renderQueue === 0) {
  23139. var sort = this.isTransparent ? right.render._distanceForSort - left.render._distanceForSort : left.render._distanceForSort - right.render._distanceForSort;
  23140. return sort + right.render.sortingFudge - left.render.sortingFudge;
  23141. }
  23142. else {
  23143. return renderQueue;
  23144. }
  23145. }
  23146. _partitionRenderObject(left, right) {
  23147. var elements = this.elements.elements;
  23148. var pivot = elements[Math.floor((right + left) / 2)];
  23149. while (left <= right) {
  23150. while (this._compare(elements[left], pivot) < 0)
  23151. left++;
  23152. while (this._compare(elements[right], pivot) > 0)
  23153. right--;
  23154. if (left < right) {
  23155. var temp = elements[left];
  23156. elements[left] = elements[right];
  23157. elements[right] = temp;
  23158. left++;
  23159. right--;
  23160. }
  23161. else if (left === right) {
  23162. left++;
  23163. break;
  23164. }
  23165. }
  23166. return left;
  23167. }
  23168. _quickSort(left, right) {
  23169. if (this.elements.length > 1) {
  23170. var index = this._partitionRenderObject(left, right);
  23171. var leftIndex = index - 1;
  23172. if (left < leftIndex)
  23173. this._quickSort(left, leftIndex);
  23174. if (index < right)
  23175. this._quickSort(index, right);
  23176. }
  23177. }
  23178. _render(context, isTarget) {
  23179. var elements = this.elements.elements;
  23180. for (var i = 0, n = this.elements.length; i < n; i++)
  23181. elements[i]._render(context, isTarget);
  23182. }
  23183. clear() {
  23184. this.elements.length = 0;
  23185. this.lastTransparentRenderElement = null;
  23186. this.lastTransparentBatched = false;
  23187. }
  23188. }
  23189. class BoundsOctreeNode {
  23190. constructor(octree, parent, baseLength, center) {
  23191. this._bounds = new BoundBox(new Vector3(), new Vector3());
  23192. this._objects = [];
  23193. this._isContaion = false;
  23194. this.center = new Vector3();
  23195. this.baseLength = 0.0;
  23196. this._setValues(octree, parent, baseLength, center);
  23197. }
  23198. static _encapsulates(outerBound, innerBound) {
  23199. return CollisionUtils.boxContainsBox(outerBound, innerBound) == ContainmentType.Contains;
  23200. }
  23201. _setValues(octree, parent, baseLength, center) {
  23202. this._octree = octree;
  23203. this._parent = parent;
  23204. this.baseLength = baseLength;
  23205. center.cloneTo(this.center);
  23206. var min = this._bounds.min;
  23207. var max = this._bounds.max;
  23208. var halfSize = (octree._looseness * baseLength) / 2;
  23209. min.setValue(center.x - halfSize, center.y - halfSize, center.z - halfSize);
  23210. max.setValue(center.x + halfSize, center.y + halfSize, center.z + halfSize);
  23211. }
  23212. _getChildBound(index) {
  23213. if (this._children != null && this._children[index]) {
  23214. return this._children[index]._bounds;
  23215. }
  23216. else {
  23217. var quarter = this.baseLength / 4;
  23218. var halfChildSize = ((this.baseLength / 2) * this._octree._looseness) / 2;
  23219. var bounds = BoundsOctreeNode._tempBoundBox;
  23220. var min = bounds.min;
  23221. var max = bounds.max;
  23222. switch (index) {
  23223. case 0:
  23224. min.x = this.center.x - quarter - halfChildSize;
  23225. min.y = this.center.y + quarter - halfChildSize;
  23226. min.z = this.center.z - quarter - halfChildSize;
  23227. max.x = this.center.x - quarter + halfChildSize;
  23228. max.y = this.center.y + quarter + halfChildSize;
  23229. max.z = this.center.z - quarter + halfChildSize;
  23230. break;
  23231. case 1:
  23232. min.x = this.center.x + quarter - halfChildSize;
  23233. min.y = this.center.y + quarter - halfChildSize;
  23234. min.z = this.center.z - quarter - halfChildSize;
  23235. max.x = this.center.x + quarter + halfChildSize;
  23236. max.y = this.center.y + quarter + halfChildSize;
  23237. max.z = this.center.z - quarter + halfChildSize;
  23238. break;
  23239. case 2:
  23240. min.x = this.center.x - quarter - halfChildSize;
  23241. min.y = this.center.y + quarter - halfChildSize;
  23242. min.z = this.center.z + quarter - halfChildSize;
  23243. max.x = this.center.x - quarter + halfChildSize;
  23244. max.y = this.center.y + quarter + halfChildSize;
  23245. max.z = this.center.z + quarter + halfChildSize;
  23246. break;
  23247. case 3:
  23248. min.x = this.center.x + quarter - halfChildSize;
  23249. min.y = this.center.y + quarter - halfChildSize;
  23250. min.z = this.center.z + quarter - halfChildSize;
  23251. max.x = this.center.x + quarter + halfChildSize;
  23252. max.y = this.center.y + quarter + halfChildSize;
  23253. max.z = this.center.z + quarter + halfChildSize;
  23254. break;
  23255. case 4:
  23256. min.x = this.center.x - quarter - halfChildSize;
  23257. min.y = this.center.y - quarter - halfChildSize;
  23258. min.z = this.center.z - quarter - halfChildSize;
  23259. max.x = this.center.x - quarter + halfChildSize;
  23260. max.y = this.center.y - quarter + halfChildSize;
  23261. max.z = this.center.z - quarter + halfChildSize;
  23262. break;
  23263. case 5:
  23264. min.x = this.center.x + quarter - halfChildSize;
  23265. min.y = this.center.y - quarter - halfChildSize;
  23266. min.z = this.center.z - quarter - halfChildSize;
  23267. max.x = this.center.x + quarter + halfChildSize;
  23268. max.y = this.center.y - quarter + halfChildSize;
  23269. max.z = this.center.z - quarter + halfChildSize;
  23270. break;
  23271. case 6:
  23272. min.x = this.center.x - quarter - halfChildSize;
  23273. min.y = this.center.y - quarter - halfChildSize;
  23274. min.z = this.center.z + quarter - halfChildSize;
  23275. max.x = this.center.x - quarter + halfChildSize;
  23276. max.y = this.center.y - quarter + halfChildSize;
  23277. max.z = this.center.z + quarter + halfChildSize;
  23278. break;
  23279. case 7:
  23280. min.x = this.center.x + quarter - halfChildSize;
  23281. min.y = this.center.y - quarter - halfChildSize;
  23282. min.z = this.center.z + quarter - halfChildSize;
  23283. max.x = this.center.x + quarter + halfChildSize;
  23284. max.y = this.center.y - quarter + halfChildSize;
  23285. max.z = this.center.z + quarter + halfChildSize;
  23286. break;
  23287. default:
  23288. }
  23289. return bounds;
  23290. }
  23291. }
  23292. _getChildCenter(index) {
  23293. if (this._children != null) {
  23294. return this._children[index].center;
  23295. }
  23296. else {
  23297. var quarter = this.baseLength / 4;
  23298. var childCenter = BoundsOctreeNode._tempVector30;
  23299. switch (index) {
  23300. case 0:
  23301. childCenter.x = this.center.x - quarter;
  23302. childCenter.y = this.center.y + quarter;
  23303. childCenter.z = this.center.z - quarter;
  23304. break;
  23305. case 1:
  23306. childCenter.x = this.center.x + quarter;
  23307. childCenter.y = this.center.y + quarter;
  23308. childCenter.z = this.center.z - quarter;
  23309. break;
  23310. case 2:
  23311. childCenter.x = this.center.x - quarter;
  23312. childCenter.y = this.center.y + quarter;
  23313. childCenter.z = this.center.z + quarter;
  23314. break;
  23315. case 3:
  23316. childCenter.x = this.center.x + quarter;
  23317. childCenter.y = this.center.y + quarter;
  23318. childCenter.z = this.center.z + quarter;
  23319. break;
  23320. case 4:
  23321. childCenter.x = this.center.x - quarter;
  23322. childCenter.y = this.center.y - quarter;
  23323. childCenter.z = this.center.z - quarter;
  23324. break;
  23325. case 5:
  23326. childCenter.x = this.center.x + quarter;
  23327. childCenter.y = this.center.y - quarter;
  23328. childCenter.z = this.center.z - quarter;
  23329. break;
  23330. case 6:
  23331. childCenter.x = this.center.x - quarter;
  23332. childCenter.y = this.center.y - quarter;
  23333. childCenter.z = this.center.z + quarter;
  23334. break;
  23335. case 7:
  23336. childCenter.x = this.center.x + quarter;
  23337. childCenter.y = this.center.y - quarter;
  23338. childCenter.z = this.center.z + quarter;
  23339. break;
  23340. default:
  23341. }
  23342. return childCenter;
  23343. }
  23344. }
  23345. _getChild(index) {
  23346. var quarter = this.baseLength / 4;
  23347. this._children || (this._children = []);
  23348. switch (index) {
  23349. case 0:
  23350. 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)));
  23351. case 1:
  23352. 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)));
  23353. case 2:
  23354. 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)));
  23355. case 3:
  23356. 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)));
  23357. case 4:
  23358. 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)));
  23359. case 5:
  23360. 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)));
  23361. case 6:
  23362. 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)));
  23363. case 7:
  23364. 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)));
  23365. default:
  23366. throw "BoundsOctreeNode: unknown index.";
  23367. }
  23368. }
  23369. _shouldMerge() {
  23370. var objectCount = this._objects.length;
  23371. for (var i = 0; i < 8; i++) {
  23372. var child = this._children[i];
  23373. if (child) {
  23374. if (child._children != null)
  23375. return false;
  23376. objectCount += child._objects.length;
  23377. }
  23378. }
  23379. return objectCount <= BoundsOctreeNode._NUM_OBJECTS_ALLOWED;
  23380. }
  23381. _mergeChildren() {
  23382. for (var i = 0; i < 8; i++) {
  23383. var child = this._children[i];
  23384. if (child) {
  23385. child._parent = null;
  23386. var childObjects = child._objects;
  23387. for (var j = childObjects.length - 1; j >= 0; j--) {
  23388. var childObject = childObjects[j];
  23389. this._objects.push(childObject);
  23390. childObject._setOctreeNode(this);
  23391. }
  23392. }
  23393. }
  23394. this._children = null;
  23395. }
  23396. _merge() {
  23397. if (this._children === null) {
  23398. var parent = this._parent;
  23399. if (parent && parent._shouldMerge()) {
  23400. parent._mergeChildren();
  23401. parent._merge();
  23402. }
  23403. }
  23404. }
  23405. _checkAddNode(object) {
  23406. if (this._children == null) {
  23407. if (this._objects.length < BoundsOctreeNode._NUM_OBJECTS_ALLOWED || (this.baseLength / 2) < this._octree._minSize) {
  23408. return this;
  23409. }
  23410. for (var i = this._objects.length - 1; i >= 0; i--) {
  23411. var existObject = this._objects[i];
  23412. var fitChildIndex = this._bestFitChild(existObject.bounds.getCenter());
  23413. if (BoundsOctreeNode._encapsulates(this._getChildBound(fitChildIndex), existObject.bounds._getBoundBox())) {
  23414. this._objects.splice(this._objects.indexOf(existObject), 1);
  23415. this._getChild(fitChildIndex)._add(existObject);
  23416. }
  23417. }
  23418. }
  23419. var newFitChildIndex = this._bestFitChild(object.bounds.getCenter());
  23420. if (BoundsOctreeNode._encapsulates(this._getChildBound(newFitChildIndex), object.bounds._getBoundBox()))
  23421. return this._getChild(newFitChildIndex)._checkAddNode(object);
  23422. else
  23423. return this;
  23424. }
  23425. _add(object) {
  23426. var addNode = this._checkAddNode(object);
  23427. addNode._objects.push(object);
  23428. object._setOctreeNode(addNode);
  23429. }
  23430. _remove(object) {
  23431. var index = this._objects.indexOf(object);
  23432. this._objects.splice(index, 1);
  23433. object._setOctreeNode(null);
  23434. this._merge();
  23435. }
  23436. _addUp(object) {
  23437. if ((CollisionUtils.boxContainsBox(this._bounds, object.bounds._getBoundBox()) === ContainmentType.Contains)) {
  23438. this._add(object);
  23439. return true;
  23440. }
  23441. else {
  23442. if (this._parent)
  23443. return this._parent._addUp(object);
  23444. else
  23445. return false;
  23446. }
  23447. }
  23448. _getCollidingWithFrustum(context, frustum, testVisible, camPos, customShader, replacementTag) {
  23449. if (testVisible) {
  23450. var type = frustum.containsBoundBox(this._bounds);
  23451. Laya.Stat.octreeNodeCulling++;
  23452. if (type === ContainmentType.Disjoint)
  23453. return;
  23454. testVisible = (type === ContainmentType.Intersects);
  23455. }
  23456. this._isContaion = !testVisible;
  23457. var camera = context.camera;
  23458. var scene = context.scene;
  23459. for (var i = 0, n = this._objects.length; i < n; i++) {
  23460. var render = this._objects[i];
  23461. if (camera._isLayerVisible(render._owner.layer) && render._enable) {
  23462. if (testVisible) {
  23463. Laya.Stat.frustumCulling++;
  23464. if (!render._needRender(frustum, context))
  23465. continue;
  23466. }
  23467. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  23468. var elements = render._renderElements;
  23469. for (var j = 0, m = elements.length; j < m; j++) {
  23470. var element = elements[j];
  23471. element._update(scene, context, customShader, replacementTag);
  23472. }
  23473. }
  23474. }
  23475. if (this._children != null) {
  23476. for (i = 0; i < 8; i++) {
  23477. var child = this._children[i];
  23478. child && child._getCollidingWithFrustum(context, frustum, testVisible, camPos, customShader, replacementTag);
  23479. }
  23480. }
  23481. }
  23482. _getCollidingWithBoundBox(checkBound, testVisible, result) {
  23483. if (testVisible) {
  23484. var type = CollisionUtils.boxContainsBox(this._bounds, checkBound);
  23485. if (type === ContainmentType.Disjoint)
  23486. return;
  23487. testVisible = (type === ContainmentType.Intersects);
  23488. }
  23489. if (testVisible) {
  23490. for (var i = 0, n = this._objects.length; i < n; i++) {
  23491. var object = this._objects[i];
  23492. if (CollisionUtils.intersectsBoxAndBox(object.bounds._getBoundBox(), checkBound)) {
  23493. result.push(object);
  23494. }
  23495. }
  23496. }
  23497. if (this._children != null) {
  23498. for (i = 0; i < 8; i++) {
  23499. var child = this._children[i];
  23500. child._getCollidingWithBoundBox(checkBound, testVisible, result);
  23501. }
  23502. }
  23503. }
  23504. _bestFitChild(boundCenter) {
  23505. return (boundCenter.x <= this.center.x ? 0 : 1) + (boundCenter.y >= this.center.y ? 0 : 4) + (boundCenter.z <= this.center.z ? 0 : 2);
  23506. }
  23507. _update(object) {
  23508. if (CollisionUtils.boxContainsBox(this._bounds, object.bounds._getBoundBox()) === ContainmentType.Contains) {
  23509. var addNode = this._checkAddNode(object);
  23510. if (addNode !== object._getOctreeNode()) {
  23511. addNode._objects.push(object);
  23512. object._setOctreeNode(addNode);
  23513. var index = this._objects.indexOf(object);
  23514. this._objects.splice(index, 1);
  23515. this._merge();
  23516. }
  23517. return true;
  23518. }
  23519. else {
  23520. if (this._parent) {
  23521. var sucess = this._parent._addUp(object);
  23522. if (sucess) {
  23523. index = this._objects.indexOf(object);
  23524. this._objects.splice(index, 1);
  23525. this._merge();
  23526. }
  23527. return sucess;
  23528. }
  23529. else {
  23530. return false;
  23531. }
  23532. }
  23533. }
  23534. add(object) {
  23535. if (!BoundsOctreeNode._encapsulates(this._bounds, object.bounds._getBoundBox()))
  23536. return false;
  23537. this._add(object);
  23538. return true;
  23539. }
  23540. remove(object) {
  23541. if (object._getOctreeNode() !== this)
  23542. return false;
  23543. this._remove(object);
  23544. return true;
  23545. }
  23546. update(object) {
  23547. if (object._getOctreeNode() !== this)
  23548. return false;
  23549. return this._update(object);
  23550. }
  23551. shrinkIfPossible(minLength) {
  23552. if (this.baseLength < minLength * 2)
  23553. return this;
  23554. var bestFit = -1;
  23555. for (var i = 0, n = this._objects.length; i < n; i++) {
  23556. var object = this._objects[i];
  23557. var newBestFit = this._bestFitChild(object.bounds.getCenter());
  23558. if (i == 0 || newBestFit == bestFit) {
  23559. var childBounds = this._getChildBound(newBestFit);
  23560. if (BoundsOctreeNode._encapsulates(childBounds, object.bounds._getBoundBox()))
  23561. (i == 0) && (bestFit = newBestFit);
  23562. else
  23563. return this;
  23564. }
  23565. else {
  23566. return this;
  23567. }
  23568. }
  23569. if (this._children != null) {
  23570. var childHadContent = false;
  23571. for (i = 0, n = this._children.length; i < n; i++) {
  23572. var child = this._children[i];
  23573. if (child && child.hasAnyObjects()) {
  23574. if (childHadContent)
  23575. return this;
  23576. if (bestFit >= 0 && bestFit != i)
  23577. return this;
  23578. childHadContent = true;
  23579. bestFit = i;
  23580. }
  23581. }
  23582. }
  23583. else {
  23584. if (bestFit != -1) {
  23585. var childCenter = this._getChildCenter(bestFit);
  23586. this._setValues(this._octree, null, this.baseLength / 2, childCenter);
  23587. }
  23588. return this;
  23589. }
  23590. if (bestFit != -1) {
  23591. var newRoot = this._children[bestFit];
  23592. newRoot._parent = null;
  23593. return newRoot;
  23594. }
  23595. else {
  23596. return this;
  23597. }
  23598. }
  23599. hasAnyObjects() {
  23600. if (this._objects.length > 0)
  23601. return true;
  23602. if (this._children != null) {
  23603. for (var i = 0; i < 8; i++) {
  23604. var child = this._children[i];
  23605. if (child && child.hasAnyObjects())
  23606. return true;
  23607. }
  23608. }
  23609. return false;
  23610. }
  23611. getCollidingWithBoundBox(checkBound, result) {
  23612. this._getCollidingWithBoundBox(checkBound, true, result);
  23613. }
  23614. getCollidingWithRay(ray, result, maxDistance = Number.MAX_VALUE) {
  23615. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, this._bounds);
  23616. if (distance == -1 || distance > maxDistance)
  23617. return;
  23618. for (var i = 0, n = this._objects.length; i < n; i++) {
  23619. var object = this._objects[i];
  23620. distance = CollisionUtils.intersectsRayAndBoxRD(ray, object.bounds._getBoundBox());
  23621. if (distance !== -1 && distance <= maxDistance)
  23622. result.push(object);
  23623. }
  23624. if (this._children != null) {
  23625. for (i = 0; i < 8; i++) {
  23626. var child = this._children[i];
  23627. child.getCollidingWithRay(ray, result, maxDistance);
  23628. }
  23629. }
  23630. }
  23631. getCollidingWithFrustum(context, customShader, replacementTag) {
  23632. var cameraPos = context.camera.transform.position;
  23633. var boundFrustum = context.camera.boundFrustum;
  23634. this._getCollidingWithFrustum(context, boundFrustum, true, cameraPos, customShader, replacementTag);
  23635. }
  23636. isCollidingWithBoundBox(checkBound) {
  23637. if (!(CollisionUtils.intersectsBoxAndBox(this._bounds, checkBound)))
  23638. return false;
  23639. for (var i = 0, n = this._objects.length; i < n; i++) {
  23640. var object = this._objects[i];
  23641. if (CollisionUtils.intersectsBoxAndBox(object.bounds._getBoundBox(), checkBound))
  23642. return true;
  23643. }
  23644. if (this._children != null) {
  23645. for (i = 0; i < 8; i++) {
  23646. var child = this._children[i];
  23647. if (child.isCollidingWithBoundBox(checkBound))
  23648. return true;
  23649. }
  23650. }
  23651. return false;
  23652. }
  23653. isCollidingWithRay(ray, maxDistance = Number.MAX_VALUE) {
  23654. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, this._bounds);
  23655. if (distance == -1 || distance > maxDistance)
  23656. return false;
  23657. for (var i = 0, n = this._objects.length; i < n; i++) {
  23658. var object = this._objects[i];
  23659. distance = CollisionUtils.intersectsRayAndBoxRD(ray, object.bounds._getBoundBox());
  23660. if (distance !== -1 && distance <= maxDistance)
  23661. return true;
  23662. }
  23663. if (this._children != null) {
  23664. for (i = 0; i < 8; i++) {
  23665. var child = this._children[i];
  23666. if (child.isCollidingWithRay(ray, maxDistance))
  23667. return true;
  23668. }
  23669. }
  23670. return false;
  23671. }
  23672. getBound() {
  23673. return this._bounds;
  23674. }
  23675. drawAllBounds(debugLine, currentDepth, maxDepth) {
  23676. if (this._children === null && this._objects.length == 0)
  23677. return;
  23678. currentDepth++;
  23679. var color = BoundsOctreeNode._tempColor0;
  23680. if (this._isContaion) {
  23681. color.r = 0.0;
  23682. color.g = 0.0;
  23683. color.b = 1.0;
  23684. }
  23685. else {
  23686. var tint = maxDepth ? currentDepth / maxDepth : 0;
  23687. color.r = 1.0 - tint;
  23688. color.g = tint;
  23689. color.b = 0.0;
  23690. }
  23691. color.a = 0.3;
  23692. Utils3D._drawBound(debugLine, this._bounds, color);
  23693. if (this._children != null) {
  23694. for (var i = 0; i < 8; i++) {
  23695. var child = this._children[i];
  23696. child && child.drawAllBounds(debugLine, currentDepth, maxDepth);
  23697. }
  23698. }
  23699. }
  23700. drawAllObjects(debugLine, currentDepth, maxDepth) {
  23701. currentDepth++;
  23702. var color = BoundsOctreeNode._tempColor0;
  23703. if (this._isContaion) {
  23704. color.r = 0.0;
  23705. color.g = 0.0;
  23706. color.b = 1.0;
  23707. }
  23708. else {
  23709. var tint = maxDepth ? currentDepth / maxDepth : 0;
  23710. color.r = 1.0 - tint;
  23711. color.g = tint;
  23712. color.b = 0.0;
  23713. }
  23714. color.a = 1.0;
  23715. for (var i = 0, n = this._objects.length; i < n; i++)
  23716. Utils3D._drawBound(debugLine, this._objects[i].bounds._getBoundBox(), color);
  23717. if (this._children != null) {
  23718. for (i = 0; i < 8; i++) {
  23719. var child = this._children[i];
  23720. child && child.drawAllObjects(debugLine, currentDepth, maxDepth);
  23721. }
  23722. }
  23723. }
  23724. }
  23725. BoundsOctreeNode._tempVector3 = new Vector3();
  23726. BoundsOctreeNode._tempVector30 = new Vector3();
  23727. BoundsOctreeNode._tempVector31 = new Vector3();
  23728. BoundsOctreeNode._tempColor0 = new Color();
  23729. BoundsOctreeNode._tempBoundBox = new BoundBox(new Vector3(), new Vector3());
  23730. BoundsOctreeNode._NUM_OBJECTS_ALLOWED = 8;
  23731. class OctreeMotionList extends SingletonList {
  23732. constructor() {
  23733. super();
  23734. }
  23735. add(element) {
  23736. var index = element._getIndexInMotionList();
  23737. if (index !== -1)
  23738. throw "OctreeMotionList:element has in PhysicsUpdateList.";
  23739. this._add(element);
  23740. element._setIndexInMotionList(this.length++);
  23741. }
  23742. remove(element) {
  23743. var index = element._getIndexInMotionList();
  23744. this.length--;
  23745. if (index !== this.length) {
  23746. var end = this.elements[this.length];
  23747. this.elements[index] = end;
  23748. end._setIndexInMotionList(index);
  23749. }
  23750. element._setIndexInMotionList(-1);
  23751. }
  23752. }
  23753. class BoundsOctree {
  23754. constructor(initialWorldSize, initialWorldPos, minNodeSize, looseness) {
  23755. this._motionObjects = new OctreeMotionList();
  23756. this.count = 0;
  23757. if (minNodeSize > initialWorldSize) {
  23758. console.warn("Minimum node size must be at least as big as the initial world size. Was: " + minNodeSize + " Adjusted to: " + initialWorldSize);
  23759. minNodeSize = initialWorldSize;
  23760. }
  23761. this._initialSize = initialWorldSize;
  23762. this._minSize = minNodeSize;
  23763. this._looseness = Math.min(Math.max(looseness, 1.0), 2.0);
  23764. this._rootNode = new BoundsOctreeNode(this, null, initialWorldSize, initialWorldPos);
  23765. }
  23766. _getMaxDepth(node, depth) {
  23767. depth++;
  23768. var children = node._children;
  23769. if (children != null) {
  23770. var curDepth = depth;
  23771. for (var i = 0, n = children.length; i < n; i++) {
  23772. var child = children[i];
  23773. child && (depth = Math.max(this._getMaxDepth(child, curDepth), depth));
  23774. }
  23775. }
  23776. return depth;
  23777. }
  23778. _grow(growObjectCenter) {
  23779. var xDirection = growObjectCenter.x >= 0 ? 1 : -1;
  23780. var yDirection = growObjectCenter.y >= 0 ? 1 : -1;
  23781. var zDirection = growObjectCenter.z >= 0 ? 1 : -1;
  23782. var oldRoot = this._rootNode;
  23783. var half = this._rootNode.baseLength / 2;
  23784. var newLength = this._rootNode.baseLength * 2;
  23785. var rootCenter = this._rootNode.center;
  23786. var newCenter = new Vector3(rootCenter.x + xDirection * half, rootCenter.y + yDirection * half, rootCenter.z + zDirection * half);
  23787. this._rootNode = new BoundsOctreeNode(this, null, newLength, newCenter);
  23788. if (oldRoot.hasAnyObjects()) {
  23789. var rootPos = this._rootNode._bestFitChild(oldRoot.center);
  23790. var children = [];
  23791. for (var i = 0; i < 8; i++) {
  23792. if (i == rootPos) {
  23793. oldRoot._parent = this._rootNode;
  23794. children[i] = oldRoot;
  23795. }
  23796. }
  23797. this._rootNode._children = children;
  23798. }
  23799. }
  23800. add(object) {
  23801. var count = 0;
  23802. while (!this._rootNode.add(object)) {
  23803. var growCenter = BoundsOctree._tempVector30;
  23804. Vector3.subtract(object.bounds.getCenter(), this._rootNode.center, growCenter);
  23805. this._grow(growCenter);
  23806. if (++count > 20) {
  23807. throw "Aborted Add operation as it seemed to be going on forever (" + (count - 1) + ") attempts at growing the octree.";
  23808. }
  23809. }
  23810. this.count++;
  23811. }
  23812. remove(object) {
  23813. var removed = object._getOctreeNode().remove(object);
  23814. if (removed) {
  23815. this.count--;
  23816. }
  23817. return removed;
  23818. }
  23819. update(object) {
  23820. var count = 0;
  23821. var octreeNode = object._getOctreeNode();
  23822. if (octreeNode) {
  23823. while (!octreeNode._update(object)) {
  23824. var growCenter = BoundsOctree._tempVector30;
  23825. Vector3.subtract(object.bounds.getCenter(), this._rootNode.center, growCenter);
  23826. this._grow(growCenter);
  23827. if (++count > 20) {
  23828. throw "Aborted Add operation as it seemed to be going on forever (" + (count - 1) + ") attempts at growing the octree.";
  23829. }
  23830. }
  23831. return true;
  23832. }
  23833. else {
  23834. return false;
  23835. }
  23836. }
  23837. shrinkRootIfPossible() {
  23838. this._rootNode = this._rootNode.shrinkIfPossible(this._initialSize);
  23839. }
  23840. addMotionObject(object) {
  23841. this._motionObjects.add(object);
  23842. }
  23843. removeMotionObject(object) {
  23844. this._motionObjects.remove(object);
  23845. }
  23846. updateMotionObjects() {
  23847. var elements = this._motionObjects.elements;
  23848. for (var i = 0, n = this._motionObjects.length; i < n; i++) {
  23849. var object = elements[i];
  23850. this.update(object);
  23851. object._setIndexInMotionList(-1);
  23852. }
  23853. this._motionObjects.length = 0;
  23854. }
  23855. isCollidingWithBoundBox(checkBounds) {
  23856. return this._rootNode.isCollidingWithBoundBox(checkBounds);
  23857. }
  23858. isCollidingWithRay(ray, maxDistance = Number.MAX_VALUE) {
  23859. return this._rootNode.isCollidingWithRay(ray, maxDistance);
  23860. }
  23861. getCollidingWithBoundBox(checkBound, result) {
  23862. this._rootNode.getCollidingWithBoundBox(checkBound, result);
  23863. }
  23864. getCollidingWithRay(ray, result, maxDistance = Number.MAX_VALUE) {
  23865. this._rootNode.getCollidingWithRay(ray, result, maxDistance);
  23866. }
  23867. getCollidingWithFrustum(context, shader, replacementTag) {
  23868. this._rootNode.getCollidingWithFrustum(context, shader, replacementTag);
  23869. }
  23870. getMaxBounds() {
  23871. return this._rootNode.getBound();
  23872. }
  23873. drawAllBounds(pixelLine) {
  23874. var maxDepth = this._getMaxDepth(this._rootNode, -1);
  23875. this._rootNode.drawAllBounds(pixelLine, -1, maxDepth);
  23876. }
  23877. drawAllObjects(pixelLine) {
  23878. var maxDepth = this._getMaxDepth(this._rootNode, -1);
  23879. this._rootNode.drawAllObjects(pixelLine, -1, maxDepth);
  23880. }
  23881. }
  23882. BoundsOctree._tempVector30 = new Vector3();
  23883. class Scene3D extends Laya.Sprite {
  23884. constructor() {
  23885. super();
  23886. this._lightCount = 0;
  23887. this._pointLights = new LightQueue();
  23888. this._spotLights = new LightQueue();
  23889. this._directionLights = new DirectionLightQueue();
  23890. this._alternateLights = new AlternateLightQueue();
  23891. this._lightmaps = [];
  23892. this._skyRenderer = new SkyRenderer();
  23893. this._reflectionMode = 1;
  23894. this._input = new Input3D();
  23895. this._timer = Laya.ILaya.timer;
  23896. this._collsionTestList = [];
  23897. this._renders = new SimpleSingletonList();
  23898. this._opaqueQueue = new RenderQueue(false);
  23899. this._transparentQueue = new RenderQueue(true);
  23900. this._cameraPool = [];
  23901. this._animatorPool = new SimpleSingletonList();
  23902. this._scriptPool = new Array();
  23903. this._tempScriptPool = new Array();
  23904. this._needClearScriptPool = false;
  23905. this._castShadowRenders = new CastShadowList();
  23906. this.currentCreationLayer = Math.pow(2, 0);
  23907. this.enableLight = true;
  23908. this._key = new Laya.SubmitKey();
  23909. this._time = 0;
  23910. this._pickIdToSprite = new Object();
  23911. if (Physics3D._enbalePhysics)
  23912. this._physicsSimulation = new PhysicsSimulation(Scene3D.physicsSettings);
  23913. this._shaderValues = new ShaderData(null);
  23914. this.parallelSplitShadowMaps = [];
  23915. this.enableFog = false;
  23916. this.fogStart = 300;
  23917. this.fogRange = 1000;
  23918. this.fogColor = new Vector3(0.7, 0.7, 0.7);
  23919. this.ambientColor = new Vector3(0.212, 0.227, 0.259);
  23920. this.reflectionIntensity = 1.0;
  23921. (Laya.WebGL.shaderHighPrecision) && (this._shaderValues.addDefine(Shader3D.SHADERDEFINE_HIGHPRECISION));
  23922. (Config3D._config._multiLighting) || (this._shaderValues.addDefine(Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING));
  23923. if (Laya.Render.supportWebGLPlusCulling) {
  23924. this._cullingBufferIndices = new Int32Array(1024);
  23925. this._cullingBufferResult = new Int32Array(1024);
  23926. }
  23927. this._scene = this;
  23928. this._input.__init__(Laya.Render.canvas, this);
  23929. if (Scene3D.octreeCulling) {
  23930. this._octree = new BoundsOctree(Scene3D.octreeInitialSize, Scene3D.octreeInitialCenter, Scene3D.octreeMinNodeSize, Scene3D.octreeLooseness);
  23931. }
  23932. if (FrustumCulling.debugFrustumCulling) {
  23933. this._debugTool = new PixelLineSprite3D();
  23934. var lineMaterial = new PixelLineMaterial();
  23935. lineMaterial.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  23936. lineMaterial.alphaTest = false;
  23937. lineMaterial.depthWrite = false;
  23938. lineMaterial.cull = RenderState.CULL_BACK;
  23939. lineMaterial.blend = RenderState.BLEND_ENABLE_ALL;
  23940. lineMaterial.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  23941. lineMaterial.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  23942. lineMaterial.depthTest = RenderState.DEPTHTEST_LESS;
  23943. this._debugTool.pixelLineRenderer.sharedMaterial = lineMaterial;
  23944. }
  23945. }
  23946. static __init__() {
  23947. var con = Config3D._config;
  23948. var multiLighting = con._multiLighting;
  23949. if (multiLighting) {
  23950. const width = 4;
  23951. var maxLightCount = con.maxLightCount;
  23952. var clusterSlices = con.lightClusterCount;
  23953. Cluster.instance = new Cluster(clusterSlices.x, clusterSlices.y, clusterSlices.z, Math.min(con.maxLightCount, con._maxAreaLightCountPerClusterAverage));
  23954. Scene3D._lightTexture = Utils3D._createFloatTextureBuffer(width, maxLightCount);
  23955. Scene3D._lightTexture.lock = true;
  23956. Scene3D._lightPixles = new Float32Array(maxLightCount * width * 4);
  23957. }
  23958. Scene3DShaderDeclaration.SHADERDEFINE_FOG = Shader3D.getDefineByName("FOG");
  23959. Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT = Shader3D.getDefineByName("DIRECTIONLIGHT");
  23960. Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT = Shader3D.getDefineByName("POINTLIGHT");
  23961. Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT = Shader3D.getDefineByName("SPOTLIGHT");
  23962. Scene3DShaderDeclaration.SHADERDEFINE_CAST_SHADOW = Shader3D.getDefineByName("CASTSHADOW");
  23963. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM1 = Shader3D.getDefineByName("SHADOWMAP_PSSM1");
  23964. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM2 = Shader3D.getDefineByName("SHADOWMAP_PSSM2");
  23965. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM3 = Shader3D.getDefineByName("SHADOWMAP_PSSM3");
  23966. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF_NO = Shader3D.getDefineByName("SHADOWMAP_PCF_NO");
  23967. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF1 = Shader3D.getDefineByName("SHADOWMAP_PCF1");
  23968. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF2 = Shader3D.getDefineByName("SHADOWMAP_PCF2");
  23969. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF3 = Shader3D.getDefineByName("SHADOWMAP_PCF3");
  23970. Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP = Shader3D.getDefineByName("REFLECTMAP");
  23971. }
  23972. static load(url, complete) {
  23973. Laya.ILaya.loader.create(url, complete, null, Scene3D.HIERARCHY);
  23974. }
  23975. _allotPickColorByID(id, pickColor) {
  23976. var pickColorR = Math.floor(id / (255 * 255));
  23977. id -= pickColorR * 255 * 255;
  23978. var pickColorG = Math.floor(id / 255);
  23979. id -= pickColorG * 255;
  23980. var pickColorB = id;
  23981. pickColor.x = pickColorR / 255;
  23982. pickColor.y = pickColorG / 255;
  23983. pickColor.z = pickColorB / 255;
  23984. pickColor.w = 1.0;
  23985. }
  23986. _searchIDByPickColor(pickColor) {
  23987. var id = pickColor.x * 255 * 255 + pickColor.y * 255 + pickColor.z;
  23988. return id;
  23989. }
  23990. get url() {
  23991. return this._url;
  23992. }
  23993. get enableFog() {
  23994. return this._enableFog;
  23995. }
  23996. set enableFog(value) {
  23997. if (this._enableFog !== value) {
  23998. this._enableFog = value;
  23999. if (value) {
  24000. this._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_FOG);
  24001. }
  24002. else
  24003. this._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_FOG);
  24004. }
  24005. }
  24006. get fogColor() {
  24007. return this._shaderValues.getVector3(Scene3D.FOGCOLOR);
  24008. }
  24009. set fogColor(value) {
  24010. this._shaderValues.setVector3(Scene3D.FOGCOLOR, value);
  24011. }
  24012. get fogStart() {
  24013. return this._shaderValues.getNumber(Scene3D.FOGSTART);
  24014. }
  24015. set fogStart(value) {
  24016. this._shaderValues.setNumber(Scene3D.FOGSTART, value);
  24017. }
  24018. get fogRange() {
  24019. return this._shaderValues.getNumber(Scene3D.FOGRANGE);
  24020. }
  24021. set fogRange(value) {
  24022. this._shaderValues.setNumber(Scene3D.FOGRANGE, value);
  24023. }
  24024. get ambientColor() {
  24025. return this._shaderValues.getVector3(Scene3D.AMBIENTCOLOR);
  24026. }
  24027. set ambientColor(value) {
  24028. this._shaderValues.setVector3(Scene3D.AMBIENTCOLOR, value);
  24029. }
  24030. get skyRenderer() {
  24031. return this._skyRenderer;
  24032. }
  24033. get customReflection() {
  24034. return this._shaderValues.getTexture(Scene3D.REFLECTIONTEXTURE);
  24035. }
  24036. set customReflection(value) {
  24037. this._shaderValues.setTexture(Scene3D.REFLECTIONTEXTURE, value);
  24038. if (value)
  24039. this._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  24040. else
  24041. this._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  24042. }
  24043. get reflectionIntensity() {
  24044. return this._shaderValues.getNumber(Scene3D.REFLETIONINTENSITY);
  24045. }
  24046. set reflectionIntensity(value) {
  24047. value = Math.max(Math.min(value, 1.0), 0.0);
  24048. this._shaderValues.setNumber(Scene3D.REFLETIONINTENSITY, value);
  24049. }
  24050. get physicsSimulation() {
  24051. return this._physicsSimulation;
  24052. }
  24053. get reflectionMode() {
  24054. return this._reflectionMode;
  24055. }
  24056. set reflectionMode(value) {
  24057. this._reflectionMode = value;
  24058. }
  24059. get timer() {
  24060. return this._timer;
  24061. }
  24062. set timer(value) {
  24063. this._timer = value;
  24064. }
  24065. get input() {
  24066. return this._input;
  24067. }
  24068. _setLightmapToChildNode(sprite) {
  24069. if (sprite instanceof RenderableSprite3D)
  24070. sprite._render._applyLightMapParams();
  24071. var children = sprite._children;
  24072. for (var i = 0, n = children.length; i < n; i++)
  24073. this._setLightmapToChildNode(children[i]);
  24074. }
  24075. _update() {
  24076. var delta = this.timer._delta / 1000;
  24077. this._time += delta;
  24078. this._shaderValues.setNumber(Scene3D.TIME, this._time);
  24079. var simulation = this._physicsSimulation;
  24080. if (Physics3D._enbalePhysics && !PhysicsSimulation.disableSimulation) {
  24081. simulation._updatePhysicsTransformFromRender();
  24082. PhysicsComponent._addUpdateList = false;
  24083. simulation._simulate(delta);
  24084. simulation._updateCharacters();
  24085. PhysicsComponent._addUpdateList = true;
  24086. simulation._updateCollisions();
  24087. simulation._eventScripts();
  24088. }
  24089. this._input._update();
  24090. this._clearScript();
  24091. this._updateScript();
  24092. Animator._update(this);
  24093. this._lateUpdateScript();
  24094. }
  24095. _binarySearchIndexInCameraPool(camera) {
  24096. var start = 0;
  24097. var end = this._cameraPool.length - 1;
  24098. var mid;
  24099. while (start <= end) {
  24100. mid = Math.floor((start + end) / 2);
  24101. var midValue = this._cameraPool[mid]._renderingOrder;
  24102. if (midValue == camera._renderingOrder)
  24103. return mid;
  24104. else if (midValue > camera._renderingOrder)
  24105. end = mid - 1;
  24106. else
  24107. start = mid + 1;
  24108. }
  24109. return start;
  24110. }
  24111. onEnable() {
  24112. this._input._onCanvasEvent(Laya.Render.canvas);
  24113. }
  24114. onDisable() {
  24115. this._input._offCanvasEvent(Laya.Render.canvas);
  24116. }
  24117. _setCreateURL(url) {
  24118. this._url = Laya.URL.formatURL(url);
  24119. }
  24120. _getGroup() {
  24121. return this._group;
  24122. }
  24123. _setGroup(value) {
  24124. this._group = value;
  24125. }
  24126. _clearScript() {
  24127. if (this._needClearScriptPool) {
  24128. var scripts = this._scriptPool;
  24129. for (var i = 0, n = scripts.length; i < n; i++) {
  24130. var script = scripts[i];
  24131. if (script) {
  24132. script._indexInPool = this._tempScriptPool.length;
  24133. this._tempScriptPool.push(script);
  24134. }
  24135. }
  24136. this._scriptPool = this._tempScriptPool;
  24137. scripts.length = 0;
  24138. this._tempScriptPool = scripts;
  24139. this._needClearScriptPool = false;
  24140. }
  24141. }
  24142. _updateScript() {
  24143. var scripts = this._scriptPool;
  24144. for (var i = 0, n = scripts.length; i < n; i++) {
  24145. var script = scripts[i];
  24146. (script && script.enabled) && (script.onUpdate());
  24147. }
  24148. }
  24149. _lateUpdateScript() {
  24150. var scripts = this._scriptPool;
  24151. for (var i = 0, n = scripts.length; i < n; i++) {
  24152. var script = scripts[i];
  24153. (script && script.enabled) && (script.onLateUpdate());
  24154. }
  24155. }
  24156. _addScript(script) {
  24157. var scripts = this._scriptPool;
  24158. script._indexInPool = scripts.length;
  24159. scripts.push(script);
  24160. }
  24161. _removeScript(script) {
  24162. this._scriptPool[script._indexInPool] = null;
  24163. script._indexInPool = -1;
  24164. this._needClearScriptPool = true;
  24165. }
  24166. _preRenderScript() {
  24167. var scripts = this._scriptPool;
  24168. for (var i = 0, n = scripts.length; i < n; i++) {
  24169. var script = scripts[i];
  24170. (script && script.enabled) && (script.onPreRender());
  24171. }
  24172. }
  24173. _postRenderScript() {
  24174. var scripts = this._scriptPool;
  24175. for (var i = 0, n = scripts.length; i < n; i++) {
  24176. var script = scripts[i];
  24177. (script && script.enabled) && (script.onPostRender());
  24178. }
  24179. }
  24180. _prepareSceneToRender() {
  24181. var shaderValues = this._shaderValues;
  24182. var multiLighting = Config3D._config._multiLighting;
  24183. if (multiLighting) {
  24184. var ligTex = Scene3D._lightTexture;
  24185. var ligPix = Scene3D._lightPixles;
  24186. const pixelWidth = ligTex.width;
  24187. const floatWidth = pixelWidth * 4;
  24188. var curCount = 0;
  24189. var dirCount = this._directionLights._length;
  24190. var dirElements = this._directionLights._elements;
  24191. if (dirCount > 0) {
  24192. var sunLightIndex = this._directionLights.getSunLight();
  24193. for (var i = 0; i < dirCount; i++, curCount++) {
  24194. var dirLight = dirElements[i];
  24195. var dir = dirLight._direction;
  24196. var intCor = dirLight._intensityColor;
  24197. var off = floatWidth * curCount;
  24198. Vector3.scale(dirLight.color, dirLight._intensity, intCor);
  24199. dirLight.transform.worldMatrix.getForward(dir);
  24200. Vector3.normalize(dir, dir);
  24201. ligPix[off] = intCor.x;
  24202. ligPix[off + 1] = intCor.y;
  24203. ligPix[off + 2] = intCor.z;
  24204. ligPix[off + 4] = dir.x;
  24205. ligPix[off + 5] = dir.y;
  24206. ligPix[off + 6] = dir.z;
  24207. if (i == sunLightIndex) {
  24208. shaderValues.setVector3(Scene3D.SUNLIGHTDIRCOLOR, intCor);
  24209. shaderValues.setVector3(Scene3D.SUNLIGHTDIRECTION, dir);
  24210. }
  24211. }
  24212. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  24213. }
  24214. else {
  24215. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  24216. }
  24217. var poiCount = this._pointLights._length;
  24218. if (poiCount > 0) {
  24219. var poiElements = this._pointLights._elements;
  24220. for (var i = 0; i < poiCount; i++, curCount++) {
  24221. var poiLight = poiElements[i];
  24222. var pos = poiLight.transform.position;
  24223. var intCor = poiLight._intensityColor;
  24224. var off = floatWidth * curCount;
  24225. Vector3.scale(poiLight.color, poiLight._intensity, intCor);
  24226. ligPix[off] = intCor.x;
  24227. ligPix[off + 1] = intCor.y;
  24228. ligPix[off + 2] = intCor.z;
  24229. ligPix[off + 3] = poiLight.range;
  24230. ligPix[off + 4] = pos.x;
  24231. ligPix[off + 5] = pos.y;
  24232. ligPix[off + 6] = pos.z;
  24233. }
  24234. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  24235. }
  24236. else {
  24237. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  24238. }
  24239. var spoCount = this._spotLights._length;
  24240. if (spoCount > 0) {
  24241. var spoElements = this._spotLights._elements;
  24242. for (var i = 0; i < spoCount; i++, curCount++) {
  24243. var spoLight = spoElements[i];
  24244. var dir = spoLight._direction;
  24245. var pos = spoLight.transform.position;
  24246. var intCor = spoLight._intensityColor;
  24247. var off = floatWidth * curCount;
  24248. Vector3.scale(spoLight.color, spoLight._intensity, intCor);
  24249. spoLight.transform.worldMatrix.getForward(dir);
  24250. Vector3.normalize(dir, dir);
  24251. ligPix[off] = intCor.x;
  24252. ligPix[off + 1] = intCor.y;
  24253. ligPix[off + 2] = intCor.z;
  24254. ligPix[off + 3] = spoLight.range;
  24255. ligPix[off + 4] = pos.x;
  24256. ligPix[off + 5] = pos.y;
  24257. ligPix[off + 6] = pos.z;
  24258. ligPix[off + 7] = spoLight.spotAngle * Math.PI / 180;
  24259. ligPix[off + 8] = dir.x;
  24260. ligPix[off + 9] = dir.y;
  24261. ligPix[off + 10] = dir.z;
  24262. }
  24263. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  24264. }
  24265. else {
  24266. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  24267. }
  24268. (curCount > 0) && (ligTex.setSubPixels(0, 0, pixelWidth, curCount, ligPix, 0));
  24269. shaderValues.setTexture(Scene3D.LIGHTBUFFER, ligTex);
  24270. shaderValues.setInt(Scene3D.DIRECTIONLIGHTCOUNT, this._directionLights._length);
  24271. shaderValues.setTexture(Scene3D.CLUSTERBUFFER, Cluster.instance._clusterTexture);
  24272. }
  24273. else {
  24274. if (this._directionLights._length > 0) {
  24275. var dirLight = this._directionLights._elements[0];
  24276. Vector3.scale(dirLight.color, dirLight._intensity, dirLight._intensityColor);
  24277. dirLight.transform.worldMatrix.getForward(dirLight._direction);
  24278. Vector3.normalize(dirLight._direction, dirLight._direction);
  24279. shaderValues.setVector3(Scene3D.LIGHTDIRCOLOR, dirLight._intensityColor);
  24280. shaderValues.setVector3(Scene3D.LIGHTDIRECTION, dirLight._direction);
  24281. shaderValues.setVector3(Scene3D.SUNLIGHTDIRCOLOR, dirLight._intensityColor);
  24282. shaderValues.setVector3(Scene3D.SUNLIGHTDIRECTION, dirLight._direction);
  24283. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  24284. }
  24285. else {
  24286. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  24287. }
  24288. if (this._pointLights._length > 0) {
  24289. var poiLight = this._pointLights._elements[0];
  24290. Vector3.scale(poiLight.color, poiLight._intensity, poiLight._intensityColor);
  24291. shaderValues.setVector3(Scene3D.POINTLIGHTCOLOR, poiLight._intensityColor);
  24292. shaderValues.setVector3(Scene3D.POINTLIGHTPOS, poiLight.transform.position);
  24293. shaderValues.setNumber(Scene3D.POINTLIGHTRANGE, poiLight.range);
  24294. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  24295. }
  24296. else {
  24297. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  24298. }
  24299. if (this._spotLights._length > 0) {
  24300. var spotLight = this._spotLights._elements[0];
  24301. Vector3.scale(spotLight.color, spotLight._intensity, spotLight._intensityColor);
  24302. shaderValues.setVector3(Scene3D.SPOTLIGHTCOLOR, spotLight._intensityColor);
  24303. shaderValues.setVector3(Scene3D.SPOTLIGHTPOS, spotLight.transform.position);
  24304. spotLight.transform.worldMatrix.getForward(spotLight._direction);
  24305. Vector3.normalize(spotLight._direction, spotLight._direction);
  24306. shaderValues.setVector3(Scene3D.SPOTLIGHTDIRECTION, spotLight._direction);
  24307. shaderValues.setNumber(Scene3D.SPOTLIGHTRANGE, spotLight.range);
  24308. shaderValues.setNumber(Scene3D.SPOTLIGHTSPOTANGLE, spotLight.spotAngle * Math.PI / 180);
  24309. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  24310. }
  24311. else {
  24312. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  24313. }
  24314. }
  24315. }
  24316. _addCamera(camera) {
  24317. var index = this._binarySearchIndexInCameraPool(camera);
  24318. var order = camera._renderingOrder;
  24319. var count = this._cameraPool.length;
  24320. while (index < count && this._cameraPool[index]._renderingOrder <= order)
  24321. index++;
  24322. this._cameraPool.splice(index, 0, camera);
  24323. }
  24324. _removeCamera(camera) {
  24325. this._cameraPool.splice(this._cameraPool.indexOf(camera), 1);
  24326. }
  24327. _preCulling(context, camera, shader, replacementTag) {
  24328. FrustumCulling.renderObjectCulling(camera, this, context, this._renders, shader, replacementTag);
  24329. }
  24330. _clear(gl, state) {
  24331. var viewport = state.viewport;
  24332. var camera = state.camera;
  24333. var renderTexture = camera._getInternalRenderTexture();
  24334. var vpW = viewport.width;
  24335. var vpH = viewport.height;
  24336. var vpX = viewport.x;
  24337. var vpY = camera._getCanvasHeight() - viewport.y - vpH;
  24338. gl.viewport(vpX, vpY, vpW, vpH);
  24339. var flag;
  24340. var clearFlag = camera.clearFlag;
  24341. if (clearFlag === BaseCamera.CLEARFLAG_SKY && !(camera.skyRenderer._isAvailable() || this._skyRenderer._isAvailable()))
  24342. clearFlag = BaseCamera.CLEARFLAG_SOLIDCOLOR;
  24343. switch (clearFlag) {
  24344. case BaseCamera.CLEARFLAG_SOLIDCOLOR:
  24345. var clearColor = camera.clearColor;
  24346. gl.enable(gl.SCISSOR_TEST);
  24347. gl.scissor(vpX, vpY, vpW, vpH);
  24348. if (clearColor)
  24349. gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
  24350. else
  24351. gl.clearColor(0, 0, 0, 0);
  24352. if (renderTexture) {
  24353. flag = gl.COLOR_BUFFER_BIT;
  24354. switch (renderTexture.depthStencilFormat) {
  24355. case Laya.RenderTextureDepthFormat.DEPTH_16:
  24356. flag |= gl.DEPTH_BUFFER_BIT;
  24357. break;
  24358. case Laya.RenderTextureDepthFormat.STENCIL_8:
  24359. flag |= gl.STENCIL_BUFFER_BIT;
  24360. break;
  24361. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_16_8:
  24362. flag |= gl.DEPTH_BUFFER_BIT;
  24363. flag |= gl.STENCIL_BUFFER_BIT;
  24364. break;
  24365. }
  24366. }
  24367. else {
  24368. flag = gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT;
  24369. }
  24370. Laya.WebGLContext.setDepthMask(gl, true);
  24371. gl.clear(flag);
  24372. gl.disable(gl.SCISSOR_TEST);
  24373. break;
  24374. case BaseCamera.CLEARFLAG_SKY:
  24375. case BaseCamera.CLEARFLAG_DEPTHONLY:
  24376. gl.enable(gl.SCISSOR_TEST);
  24377. gl.scissor(vpX, vpY, vpW, vpH);
  24378. if (renderTexture) {
  24379. switch (renderTexture.depthStencilFormat) {
  24380. case Laya.RenderTextureDepthFormat.DEPTH_16:
  24381. flag = gl.DEPTH_BUFFER_BIT;
  24382. break;
  24383. case Laya.RenderTextureDepthFormat.STENCIL_8:
  24384. flag = gl.STENCIL_BUFFER_BIT;
  24385. break;
  24386. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_16_8:
  24387. flag = gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT;
  24388. break;
  24389. }
  24390. }
  24391. else {
  24392. flag = gl.DEPTH_BUFFER_BIT;
  24393. }
  24394. Laya.WebGLContext.setDepthMask(gl, true);
  24395. gl.clear(flag);
  24396. gl.disable(gl.SCISSOR_TEST);
  24397. break;
  24398. case BaseCamera.CLEARFLAG_NONE:
  24399. break;
  24400. default:
  24401. throw new Error("BaseScene:camera clearFlag invalid.");
  24402. }
  24403. }
  24404. _renderScene(context) {
  24405. var camera = context.camera;
  24406. var renderTar = camera._getInternalRenderTexture();
  24407. renderTar ? this._opaqueQueue._render(context, true) : this._opaqueQueue._render(context, false);
  24408. if (camera.clearFlag === BaseCamera.CLEARFLAG_SKY) {
  24409. if (camera.skyRenderer._isAvailable())
  24410. camera.skyRenderer._render(context);
  24411. else if (this._skyRenderer._isAvailable())
  24412. this._skyRenderer._render(context);
  24413. }
  24414. renderTar ? this._transparentQueue._render(context, true) : this._transparentQueue._render(context, false);
  24415. if (FrustumCulling.debugFrustumCulling) {
  24416. var renderElements = this._debugTool._render._renderElements;
  24417. for (var i = 0, n = renderElements.length; i < n; i++) {
  24418. renderElements[i]._update(this, context, null, null);
  24419. renderElements[i]._render(context, false);
  24420. }
  24421. }
  24422. }
  24423. _parse(data, spriteMap) {
  24424. var lightMapsData = data.lightmaps;
  24425. if (lightMapsData) {
  24426. var lightMapCount = lightMapsData.length;
  24427. var lightmaps = [];
  24428. for (var i = 0; i < lightMapCount; i++)
  24429. lightmaps[i] = Laya.Loader.getRes(lightMapsData[i].path);
  24430. this.setlightmaps(lightmaps);
  24431. }
  24432. var ambientColorData = data.ambientColor;
  24433. if (ambientColorData) {
  24434. var ambCol = this.ambientColor;
  24435. ambCol.fromArray(ambientColorData);
  24436. this.ambientColor = ambCol;
  24437. }
  24438. var skyData = data.sky;
  24439. if (skyData) {
  24440. this._skyRenderer.material = Laya.Loader.getRes(skyData.material.path);
  24441. switch (skyData.mesh) {
  24442. case "SkyBox":
  24443. this._skyRenderer.mesh = SkyBox.instance;
  24444. break;
  24445. case "SkyDome":
  24446. this._skyRenderer.mesh = SkyDome.instance;
  24447. break;
  24448. default:
  24449. this.skyRenderer.mesh = SkyBox.instance;
  24450. }
  24451. }
  24452. var reflectionTextureData = data.reflectionTexture;
  24453. reflectionTextureData && (this.customReflection = Laya.Loader.getRes(reflectionTextureData));
  24454. this.enableFog = data.enableFog;
  24455. this.fogStart = data.fogStart;
  24456. this.fogRange = data.fogRange;
  24457. var fogColorData = data.fogColor;
  24458. if (fogColorData) {
  24459. var fogCol = this.fogColor;
  24460. fogCol.fromArray(fogColorData);
  24461. this.fogColor = fogCol;
  24462. }
  24463. }
  24464. _onActive() {
  24465. super._onActive();
  24466. Laya.ILaya.stage._scene3Ds.push(this);
  24467. }
  24468. _onInActive() {
  24469. super._onInActive();
  24470. var scenes = Laya.ILaya.stage._scene3Ds;
  24471. scenes.splice(scenes.indexOf(this), 1);
  24472. }
  24473. _addRenderObject(render) {
  24474. if (this._octree && render._supportOctree) {
  24475. this._octree.add(render);
  24476. }
  24477. else {
  24478. this._renders.add(render);
  24479. if (Laya.Render.supportWebGLPlusCulling) {
  24480. var indexInList = render._getIndexInList();
  24481. var length = this._cullingBufferIndices.length;
  24482. if (indexInList >= length) {
  24483. var tempIndices = this._cullingBufferIndices;
  24484. var tempResult = this._cullingBufferResult;
  24485. this._cullingBufferIndices = new Int32Array(length + 1024);
  24486. this._cullingBufferResult = new Int32Array(length + 1024);
  24487. this._cullingBufferIndices.set(tempIndices, 0);
  24488. this._cullingBufferResult.set(tempResult, 0);
  24489. }
  24490. this._cullingBufferIndices[indexInList] = render._cullingBufferIndex;
  24491. }
  24492. }
  24493. }
  24494. _removeRenderObject(render) {
  24495. if (this._octree && render._supportOctree) {
  24496. this._octree.remove(render);
  24497. }
  24498. else {
  24499. var endRender;
  24500. if (Laya.Render.supportWebGLPlusCulling) {
  24501. endRender = this._renders.elements[this._renders.length - 1];
  24502. }
  24503. this._renders.remove(render);
  24504. if (Laya.Render.supportWebGLPlusCulling) {
  24505. this._cullingBufferIndices[endRender._getIndexInList()] = endRender._cullingBufferIndex;
  24506. }
  24507. }
  24508. }
  24509. _addShadowCastRenderObject(render) {
  24510. if (this._octree) ;
  24511. else {
  24512. this._castShadowRenders.add(render);
  24513. }
  24514. }
  24515. _removeShadowCastRenderObject(render) {
  24516. if (this._octree) ;
  24517. else {
  24518. this._castShadowRenders.remove(render);
  24519. }
  24520. }
  24521. _getRenderQueue(index) {
  24522. if (index <= 2500)
  24523. return this._opaqueQueue;
  24524. else
  24525. return this._transparentQueue;
  24526. }
  24527. setlightmaps(value) {
  24528. var maps = this._lightmaps;
  24529. for (var i = 0, n = maps.length; i < n; i++)
  24530. maps[i]._removeReference();
  24531. if (value) {
  24532. var count = value.length;
  24533. maps.length = count;
  24534. for (i = 0; i < count; i++) {
  24535. var lightMap = value[i];
  24536. lightMap._addReference();
  24537. maps[i] = lightMap;
  24538. }
  24539. }
  24540. else {
  24541. throw new Error("Scene3D: value value can't be null.");
  24542. }
  24543. for (i = 0, n = this._children.length; i < n; i++)
  24544. this._setLightmapToChildNode(this._children[i]);
  24545. }
  24546. getlightmaps() {
  24547. return this._lightmaps.slice();
  24548. }
  24549. destroy(destroyChild = true) {
  24550. if (this.destroyed)
  24551. return;
  24552. super.destroy(destroyChild);
  24553. this._skyRenderer.destroy();
  24554. this._skyRenderer = null;
  24555. this._directionLights = null;
  24556. this._pointLights = null;
  24557. this._spotLights = null;
  24558. this._alternateLights = null;
  24559. this._lightmaps = null;
  24560. this._shaderValues = null;
  24561. this._renders = null;
  24562. this._castShadowRenders = null;
  24563. this._cameraPool = null;
  24564. this._octree = null;
  24565. this.parallelSplitShadowMaps = null;
  24566. this._physicsSimulation && this._physicsSimulation._destroy();
  24567. Laya.Loader.clearRes(this.url);
  24568. }
  24569. render(ctx, x, y) {
  24570. ctx._curSubmit = Laya.SubmitBase.RENDERBASE;
  24571. this._children.length > 0 && ctx.addRenderObject(this);
  24572. }
  24573. renderSubmit() {
  24574. var gl = Laya.LayaGL.instance;
  24575. this._prepareSceneToRender();
  24576. var i, n, n1;
  24577. for (i = 0, n = this._cameraPool.length, n1 = n - 1; i < n; i++) {
  24578. if (Laya.Render.supportWebGLPlusRendering)
  24579. ShaderData.setRuntimeValueMode((i == n1) ? true : false);
  24580. var camera = this._cameraPool[i];
  24581. camera.enableRender && camera.render();
  24582. }
  24583. Laya.Context.set2DRenderConfig();
  24584. return 1;
  24585. }
  24586. getRenderType() {
  24587. return 0;
  24588. }
  24589. releaseRender() {
  24590. }
  24591. reUse(context, pos) {
  24592. return 0;
  24593. }
  24594. }
  24595. Scene3D.HIERARCHY = "HIERARCHY";
  24596. Scene3D.physicsSettings = new PhysicsSettings();
  24597. Scene3D.octreeCulling = false;
  24598. Scene3D.octreeInitialSize = 64.0;
  24599. Scene3D.octreeInitialCenter = new Vector3(0, 0, 0);
  24600. Scene3D.octreeMinNodeSize = 2.0;
  24601. Scene3D.octreeLooseness = 1.25;
  24602. Scene3D.REFLECTIONMODE_SKYBOX = 0;
  24603. Scene3D.REFLECTIONMODE_CUSTOM = 1;
  24604. Scene3D.FOGCOLOR = Shader3D.propertyNameToID("u_FogColor");
  24605. Scene3D.FOGSTART = Shader3D.propertyNameToID("u_FogStart");
  24606. Scene3D.FOGRANGE = Shader3D.propertyNameToID("u_FogRange");
  24607. Scene3D.DIRECTIONLIGHTCOUNT = Shader3D.propertyNameToID("u_DirationLightCount");
  24608. Scene3D.LIGHTBUFFER = Shader3D.propertyNameToID("u_LightBuffer");
  24609. Scene3D.CLUSTERBUFFER = Shader3D.propertyNameToID("u_LightClusterBuffer");
  24610. Scene3D.SUNLIGHTDIRECTION = Shader3D.propertyNameToID("u_SunLight.direction");
  24611. Scene3D.SUNLIGHTDIRCOLOR = Shader3D.propertyNameToID("u_SunLight.color");
  24612. Scene3D.LIGHTDIRECTION = Shader3D.propertyNameToID("u_DirectionLight.direction");
  24613. Scene3D.LIGHTDIRCOLOR = Shader3D.propertyNameToID("u_DirectionLight.color");
  24614. Scene3D.POINTLIGHTPOS = Shader3D.propertyNameToID("u_PointLight.position");
  24615. Scene3D.POINTLIGHTRANGE = Shader3D.propertyNameToID("u_PointLight.range");
  24616. Scene3D.POINTLIGHTATTENUATION = Shader3D.propertyNameToID("u_PointLight.attenuation");
  24617. Scene3D.POINTLIGHTCOLOR = Shader3D.propertyNameToID("u_PointLight.color");
  24618. Scene3D.SPOTLIGHTPOS = Shader3D.propertyNameToID("u_SpotLight.position");
  24619. Scene3D.SPOTLIGHTDIRECTION = Shader3D.propertyNameToID("u_SpotLight.direction");
  24620. Scene3D.SPOTLIGHTSPOTANGLE = Shader3D.propertyNameToID("u_SpotLight.spot");
  24621. Scene3D.SPOTLIGHTRANGE = Shader3D.propertyNameToID("u_SpotLight.range");
  24622. Scene3D.SPOTLIGHTCOLOR = Shader3D.propertyNameToID("u_SpotLight.color");
  24623. Scene3D.SHADOWDISTANCE = Shader3D.propertyNameToID("u_shadowPSSMDistance");
  24624. Scene3D.SHADOWLIGHTVIEWPROJECT = Shader3D.propertyNameToID("u_lightShadowVP");
  24625. Scene3D.SHADOWMAPPCFOFFSET = Shader3D.propertyNameToID("u_shadowPCFoffset");
  24626. Scene3D.SHADOWMAPTEXTURE1 = Shader3D.propertyNameToID("u_shadowMap1");
  24627. Scene3D.SHADOWMAPTEXTURE2 = Shader3D.propertyNameToID("u_shadowMap2");
  24628. Scene3D.SHADOWMAPTEXTURE3 = Shader3D.propertyNameToID("u_shadowMap3");
  24629. Scene3D.AMBIENTCOLOR = Shader3D.propertyNameToID("u_AmbientColor");
  24630. Scene3D.REFLECTIONTEXTURE = Shader3D.propertyNameToID("u_ReflectTexture");
  24631. Scene3D.REFLETIONINTENSITY = Shader3D.propertyNameToID("u_ReflectIntensity");
  24632. Scene3D.TIME = Shader3D.propertyNameToID("u_Time");
  24633. class SkinnedMeshSprite3DShaderDeclaration {
  24634. }
  24635. class SkinnedMeshRenderer extends MeshRenderer {
  24636. constructor(owner) {
  24637. super(owner);
  24638. this._bones = [];
  24639. this._skinnedDataLoopMarks = [];
  24640. this._localBounds = new Bounds(Vector3._ZERO, Vector3._ZERO);
  24641. this._cacheAnimationNode = [];
  24642. }
  24643. get localBounds() {
  24644. return this._localBounds;
  24645. }
  24646. set localBounds(value) {
  24647. this._localBounds = value;
  24648. }
  24649. get rootBone() {
  24650. return this._cacheRootBone;
  24651. }
  24652. set rootBone(value) {
  24653. if (this._cacheRootBone != value) {
  24654. if (this._cacheRootBone)
  24655. this._cacheRootBone.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  24656. else
  24657. this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  24658. if (value)
  24659. value.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  24660. else
  24661. this._owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  24662. this._cacheRootBone = value;
  24663. this._onWorldMatNeedChange(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE);
  24664. }
  24665. }
  24666. get bones() {
  24667. return this._bones;
  24668. }
  24669. _computeSkinnedData() {
  24670. if (this._cacheMesh && this._cacheAvatar || this._cacheMesh && !this._cacheAvatar) {
  24671. var bindPoses = this._cacheMesh._inverseBindPoses;
  24672. var meshBindPoseIndices = this._cacheMesh._bindPoseIndices;
  24673. var pathMarks = this._cacheMesh._skinDataPathMarks;
  24674. for (var i = 0, n = this._cacheMesh.subMeshCount; i < n; i++) {
  24675. var subMeshBoneIndices = this._cacheMesh.getSubMesh(i)._boneIndicesList;
  24676. var subData = this._skinnedData[i];
  24677. for (var j = 0, m = subMeshBoneIndices.length; j < m; j++) {
  24678. var boneIndices = subMeshBoneIndices[j];
  24679. this._computeSubSkinnedData(bindPoses, boneIndices, meshBindPoseIndices, subData[j], pathMarks);
  24680. }
  24681. }
  24682. }
  24683. }
  24684. _computeSubSkinnedData(bindPoses, boneIndices, meshBindPoseInices, data, pathMarks) {
  24685. for (var k = 0, q = boneIndices.length; k < q; k++) {
  24686. var index = boneIndices[k];
  24687. if (this._skinnedDataLoopMarks[index] === Laya.Stat.loopCount) {
  24688. var p = pathMarks[index];
  24689. var preData = this._skinnedData[p[0]][p[1]];
  24690. var srcIndex = p[2] * 16;
  24691. var dstIndex = k * 16;
  24692. for (var d = 0; d < 16; d++)
  24693. data[dstIndex + d] = preData[srcIndex + d];
  24694. }
  24695. else {
  24696. if (!this._cacheAvatar) {
  24697. var boneIndex = meshBindPoseInices[index];
  24698. Utils3D._mulMatrixArray(this._bones[boneIndex].transform.worldMatrix.elements, bindPoses[boneIndex], data, k * 16);
  24699. }
  24700. else {
  24701. Utils3D._mulMatrixArray(this._cacheAnimationNode[index].transform.getWorldMatrix(), bindPoses[meshBindPoseInices[index]], data, k * 16);
  24702. }
  24703. this._skinnedDataLoopMarks[index] = Laya.Stat.loopCount;
  24704. }
  24705. }
  24706. }
  24707. _onWorldMatNeedChange(flag) {
  24708. this._boundsChange = true;
  24709. if (this._octreeNode) {
  24710. if (this._cacheAvatar) {
  24711. if (this._indexInOctreeMotionList === -1)
  24712. this._octreeNode._octree.addMotionObject(this);
  24713. }
  24714. else {
  24715. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  24716. if (flag) {
  24717. if (this._indexInOctreeMotionList === -1)
  24718. this._octreeNode._octree.addMotionObject(this);
  24719. }
  24720. }
  24721. }
  24722. }
  24723. _createRenderElement() {
  24724. return new RenderElement();
  24725. }
  24726. _onMeshChange(value) {
  24727. super._onMeshChange(value);
  24728. this._cacheMesh = value;
  24729. var subMeshCount = value.subMeshCount;
  24730. this._skinnedData = [];
  24731. this._skinnedDataLoopMarks.length = value._bindPoseIndices.length;
  24732. for (var i = 0; i < subMeshCount; i++) {
  24733. var subBoneIndices = value.getSubMesh(i)._boneIndicesList;
  24734. var subCount = subBoneIndices.length;
  24735. var subData = this._skinnedData[i] = [];
  24736. for (var j = 0; j < subCount; j++)
  24737. subData[j] = new Float32Array(subBoneIndices[j].length * 16);
  24738. }
  24739. (this._cacheAvatar && value) && (this._getCacheAnimationNodes());
  24740. }
  24741. _setCacheAnimator(animator) {
  24742. this._cacheAnimator = animator;
  24743. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE);
  24744. this._setRootNode();
  24745. }
  24746. _calculateBoundingBox() {
  24747. if (!this._cacheAvatar) {
  24748. if (this._cacheRootBone)
  24749. this._localBounds._tranform(this._cacheRootBone.transform.worldMatrix, this._bounds);
  24750. else
  24751. this._localBounds._tranform(this._owner.transform.worldMatrix, this._bounds);
  24752. }
  24753. else {
  24754. if (this._cacheAnimator && this._rootBone) {
  24755. var worldMat = SkinnedMeshRenderer._tempMatrix4x4;
  24756. Utils3D.matrix4x4MultiplyMFM(this._cacheAnimator.owner.transform.worldMatrix, this._cacheRootAnimationNode.transform.getWorldMatrix(), worldMat);
  24757. this._localBounds._tranform(worldMat, this._bounds);
  24758. }
  24759. else {
  24760. super._calculateBoundingBox();
  24761. }
  24762. }
  24763. if (Laya.Render.supportWebGLPlusCulling) {
  24764. var min = this._bounds.getMin();
  24765. var max = this._bounds.getMax();
  24766. var buffer = FrustumCulling._cullingBuffer;
  24767. buffer[this._cullingBufferIndex + 1] = min.x;
  24768. buffer[this._cullingBufferIndex + 2] = min.y;
  24769. buffer[this._cullingBufferIndex + 3] = min.z;
  24770. buffer[this._cullingBufferIndex + 4] = max.x;
  24771. buffer[this._cullingBufferIndex + 5] = max.y;
  24772. buffer[this._cullingBufferIndex + 6] = max.z;
  24773. }
  24774. }
  24775. _renderUpdate(context, transform) {
  24776. if (this._cacheAnimator) {
  24777. this._computeSkinnedData();
  24778. if (!this._cacheAvatar) {
  24779. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  24780. }
  24781. else {
  24782. var aniOwnerTrans = this._cacheAnimator.owner._transform;
  24783. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, aniOwnerTrans.worldMatrix);
  24784. }
  24785. }
  24786. else {
  24787. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  24788. }
  24789. }
  24790. _renderUpdateWithCamera(context, transform) {
  24791. var projectionView = context.projectionViewMatrix;
  24792. if (this._cacheAnimator) {
  24793. if (!this._cacheAvatar) {
  24794. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  24795. }
  24796. else {
  24797. var aniOwnerTrans = this._cacheAnimator.owner._transform;
  24798. Matrix4x4.multiply(projectionView, aniOwnerTrans.worldMatrix, this._projectionViewWorldMatrix);
  24799. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  24800. }
  24801. }
  24802. else {
  24803. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  24804. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  24805. }
  24806. }
  24807. _destroy() {
  24808. super._destroy();
  24809. if (!this._cacheAvatar) {
  24810. if (this._cacheRootBone)
  24811. (!this._cacheRootBone.destroyed) && (this._cacheRootBone.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  24812. else
  24813. (this._owner && !this._owner.destroyed) && (this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  24814. }
  24815. else {
  24816. if (this._cacheRootAnimationNode)
  24817. this._cacheRootAnimationNode.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  24818. }
  24819. }
  24820. get bounds() {
  24821. if (this._boundsChange || this._cacheAvatar) {
  24822. this._calculateBoundingBox();
  24823. this._boundsChange = false;
  24824. }
  24825. return this._bounds;
  24826. }
  24827. _setRootBone(name) {
  24828. this._rootBone = name;
  24829. this._setRootNode();
  24830. }
  24831. _setRootNode() {
  24832. var rootNode;
  24833. if (this._cacheAnimator && this._rootBone && this._cacheAvatar)
  24834. rootNode = this._cacheAnimator._avatarNodeMap[this._rootBone];
  24835. else
  24836. rootNode = null;
  24837. if (this._cacheRootAnimationNode != rootNode) {
  24838. this._onWorldMatNeedChange(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE);
  24839. this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  24840. if (this._cacheRootAnimationNode)
  24841. this._cacheRootAnimationNode.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  24842. (rootNode) && (rootNode.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  24843. this._cacheRootAnimationNode = rootNode;
  24844. }
  24845. }
  24846. _getCacheAnimationNodes() {
  24847. var meshBoneNames = this._cacheMesh._boneNames;
  24848. var bindPoseIndices = this._cacheMesh._bindPoseIndices;
  24849. var innerBindPoseCount = bindPoseIndices.length;
  24850. if (!Laya.Render.supportWebGLPlusAnimation) {
  24851. this._cacheAnimationNode.length = innerBindPoseCount;
  24852. var nodeMap = this._cacheAnimator._avatarNodeMap;
  24853. for (var i = 0; i < innerBindPoseCount; i++) {
  24854. var node = nodeMap[meshBoneNames[bindPoseIndices[i]]];
  24855. this._cacheAnimationNode[i] = node;
  24856. }
  24857. }
  24858. else {
  24859. this._cacheAnimationNodeIndices = new Uint16Array(innerBindPoseCount);
  24860. var nodeMapC = this._cacheAnimator._avatarNodeMap;
  24861. for (i = 0; i < innerBindPoseCount; i++) {
  24862. var nodeC = nodeMapC[meshBoneNames[bindPoseIndices[i]]];
  24863. this._cacheAnimationNodeIndices[i] = nodeC ? nodeC._worldMatrixIndex : 0;
  24864. }
  24865. }
  24866. }
  24867. _setCacheAvatar(value) {
  24868. if (this._cacheAvatar !== value) {
  24869. if (this._cacheMesh) {
  24870. this._cacheAvatar = value;
  24871. if (value) {
  24872. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE);
  24873. this._getCacheAnimationNodes();
  24874. }
  24875. }
  24876. else {
  24877. this._cacheAvatar = value;
  24878. }
  24879. this._setRootNode();
  24880. }
  24881. }
  24882. _computeSubSkinnedDataNative(worldMatrixs, cacheAnimationNodeIndices, inverseBindPosesBuffer, boneIndices, bindPoseInices, data) {
  24883. Laya.LayaGL.instance.computeSubSkinnedData(worldMatrixs, cacheAnimationNodeIndices, inverseBindPosesBuffer, boneIndices, bindPoseInices, data);
  24884. }
  24885. _computeSkinnedDataForNative() {
  24886. if (this._cacheMesh && this._cacheAvatar || this._cacheMesh && !this._cacheAvatar) {
  24887. var bindPoses = this._cacheMesh._inverseBindPoses;
  24888. var meshBindPoseIndices = this._cacheMesh._bindPoseIndices;
  24889. var pathMarks = this._cacheMesh._skinDataPathMarks;
  24890. for (var i = 0, n = this._cacheMesh.subMeshCount; i < n; i++) {
  24891. var subMeshBoneIndices = this._cacheMesh.getSubMesh(i)._boneIndicesList;
  24892. var subData = this._skinnedData[i];
  24893. for (var j = 0, m = subMeshBoneIndices.length; j < m; j++) {
  24894. var boneIndices = subMeshBoneIndices[j];
  24895. if (this._cacheAvatar && Laya.Render.supportWebGLPlusAnimation)
  24896. this._computeSubSkinnedDataNative(this._cacheAnimator._animationNodeWorldMatrixs, this._cacheAnimationNodeIndices, this._cacheMesh._inverseBindPosesBuffer, boneIndices, meshBindPoseIndices, subData[j]);
  24897. else
  24898. this._computeSubSkinnedData(bindPoses, boneIndices, meshBindPoseIndices, subData[j], pathMarks);
  24899. }
  24900. }
  24901. }
  24902. }
  24903. }
  24904. SkinnedMeshRenderer._tempMatrix4x4 = new Matrix4x4();
  24905. class SkinnedMeshSprite3D extends RenderableSprite3D {
  24906. constructor(mesh = null, name = null) {
  24907. super(name);
  24908. this._meshFilter = new MeshFilter(this);
  24909. this._render = new SkinnedMeshRenderer(this);
  24910. (mesh) && (this._meshFilter.sharedMesh = mesh);
  24911. }
  24912. static __init__() {
  24913. SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE = Shader3D.getDefineByName("BONE");
  24914. }
  24915. get meshFilter() {
  24916. return this._meshFilter;
  24917. }
  24918. get skinnedMeshRenderer() {
  24919. return this._render;
  24920. }
  24921. _parse(data, spriteMap) {
  24922. super._parse(data, spriteMap);
  24923. var render = this.skinnedMeshRenderer;
  24924. var lightmapIndex = data.lightmapIndex;
  24925. (lightmapIndex != null) && (render.lightmapIndex = lightmapIndex);
  24926. var lightmapScaleOffsetArray = data.lightmapScaleOffset;
  24927. (lightmapScaleOffsetArray) && (render.lightmapScaleOffset = new Vector4(lightmapScaleOffsetArray[0], lightmapScaleOffsetArray[1], lightmapScaleOffsetArray[2], lightmapScaleOffsetArray[3]));
  24928. var meshPath;
  24929. meshPath = data.meshPath;
  24930. if (meshPath) {
  24931. var mesh = Laya.Loader.getRes(meshPath);
  24932. (mesh) && (this.meshFilter.sharedMesh = mesh);
  24933. }
  24934. var materials = data.materials;
  24935. if (materials) {
  24936. var sharedMaterials = render.sharedMaterials;
  24937. var materialCount = materials.length;
  24938. sharedMaterials.length = materialCount;
  24939. for (var i = 0; i < materialCount; i++) {
  24940. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  24941. }
  24942. render.sharedMaterials = sharedMaterials;
  24943. }
  24944. var boundBox = data.boundBox;
  24945. var min = boundBox.min;
  24946. var max = boundBox.max;
  24947. render.localBounds.setMin(new Vector3(min[0], min[1], min[2]));
  24948. render.localBounds.setMax(new Vector3(max[0], max[1], max[2]));
  24949. if (spriteMap) {
  24950. var rootBoneData = data.rootBone;
  24951. render.rootBone = spriteMap[rootBoneData];
  24952. var bonesData = data.bones;
  24953. var n;
  24954. for (i = 0, n = bonesData.length; i < n; i++)
  24955. render.bones.push(spriteMap[bonesData[i]]);
  24956. }
  24957. else {
  24958. (data.rootBone) && (render._setRootBone(data.rootBone));
  24959. }
  24960. }
  24961. _changeHierarchyAnimator(animator) {
  24962. super._changeHierarchyAnimator(animator);
  24963. this.skinnedMeshRenderer._setCacheAnimator(animator);
  24964. }
  24965. _changeAnimatorAvatar(avatar) {
  24966. this.skinnedMeshRenderer._setCacheAvatar(avatar);
  24967. }
  24968. _cloneTo(destObject, srcRoot, dstRoot) {
  24969. var meshSprite3D = destObject;
  24970. meshSprite3D.meshFilter.sharedMesh = this.meshFilter.sharedMesh;
  24971. var meshRender = this._render;
  24972. var destMeshRender = meshSprite3D._render;
  24973. destMeshRender.enable = meshRender.enable;
  24974. destMeshRender.sharedMaterials = meshRender.sharedMaterials;
  24975. destMeshRender.castShadow = meshRender.castShadow;
  24976. var lightmapScaleOffset = meshRender.lightmapScaleOffset;
  24977. lightmapScaleOffset && (destMeshRender.lightmapScaleOffset = lightmapScaleOffset.clone());
  24978. destMeshRender.receiveShadow = meshRender.receiveShadow;
  24979. destMeshRender.sortingFudge = meshRender.sortingFudge;
  24980. destMeshRender._rootBone = meshRender._rootBone;
  24981. var bones = meshRender.bones;
  24982. var destBones = destMeshRender.bones;
  24983. var bonesCount = bones.length;
  24984. destBones.length = bonesCount;
  24985. var rootBone = meshRender.rootBone;
  24986. if (rootBone) {
  24987. var pathes = Utils3D._getHierarchyPath(srcRoot, rootBone, SkinnedMeshSprite3D._tempArray0);
  24988. if (pathes)
  24989. destMeshRender.rootBone = Utils3D._getNodeByHierarchyPath(dstRoot, pathes);
  24990. else
  24991. destMeshRender.rootBone = rootBone;
  24992. }
  24993. for (var i = 0; i < bones.length; i++) {
  24994. pathes = Utils3D._getHierarchyPath(srcRoot, bones[i], SkinnedMeshSprite3D._tempArray0);
  24995. if (pathes)
  24996. destBones[i] = Utils3D._getNodeByHierarchyPath(dstRoot, pathes);
  24997. else
  24998. destBones[i] = bones[i];
  24999. }
  25000. var lbb = meshRender.localBounds;
  25001. (lbb) && (lbb.cloneTo(destMeshRender.localBounds));
  25002. super._cloneTo(destObject, srcRoot, dstRoot);
  25003. }
  25004. destroy(destroyChild = true) {
  25005. if (this.destroyed)
  25006. return;
  25007. super.destroy(destroyChild);
  25008. this._meshFilter.destroy();
  25009. }
  25010. _create() {
  25011. return new SkinnedMeshSprite3D();
  25012. }
  25013. }
  25014. SkinnedMeshSprite3D._tempArray0 = [];
  25015. SkinnedMeshSprite3D.BONES = Shader3D.propertyNameToID("u_Bones");
  25016. class TrailMaterial extends BaseMaterial {
  25017. constructor() {
  25018. super();
  25019. this.setShaderName("Trail");
  25020. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  25021. this._shaderValues.setVector(TrailMaterial.TINTCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  25022. this.renderMode = TrailMaterial.RENDERMODE_ALPHABLENDED;
  25023. }
  25024. static __initDefine__() {
  25025. TrailMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  25026. TrailMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  25027. TrailMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  25028. }
  25029. get _TintColorR() {
  25030. return this._color.x;
  25031. }
  25032. set _TintColorR(value) {
  25033. this._color.x = value;
  25034. this.color = this._color;
  25035. }
  25036. get _TintColorG() {
  25037. return this._color.y;
  25038. }
  25039. set _TintColorG(value) {
  25040. this._color.y = value;
  25041. this.color = this._color;
  25042. }
  25043. get _TintColorB() {
  25044. return this._color.z;
  25045. }
  25046. set _TintColorB(value) {
  25047. this._color.z = value;
  25048. this.color = this._color;
  25049. }
  25050. get _TintColorA() {
  25051. return this._color.w;
  25052. }
  25053. set _TintColorA(value) {
  25054. this._color.w = value;
  25055. this.color = this._color;
  25056. }
  25057. get _MainTex_STX() {
  25058. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).x;
  25059. }
  25060. set _MainTex_STX(x) {
  25061. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  25062. tilOff.x = x;
  25063. this.tilingOffset = tilOff;
  25064. }
  25065. get _MainTex_STY() {
  25066. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).y;
  25067. }
  25068. set _MainTex_STY(y) {
  25069. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  25070. tilOff.y = y;
  25071. this.tilingOffset = tilOff;
  25072. }
  25073. get _MainTex_STZ() {
  25074. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).z;
  25075. }
  25076. set _MainTex_STZ(z) {
  25077. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  25078. tilOff.z = z;
  25079. this.tilingOffset = tilOff;
  25080. }
  25081. get _MainTex_STW() {
  25082. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).w;
  25083. }
  25084. set _MainTex_STW(w) {
  25085. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  25086. tilOff.w = w;
  25087. this.tilingOffset = tilOff;
  25088. }
  25089. set renderMode(value) {
  25090. switch (value) {
  25091. case TrailMaterial.RENDERMODE_ADDTIVE:
  25092. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  25093. this.alphaTest = false;
  25094. this.depthWrite = false;
  25095. this.cull = RenderState.CULL_NONE;
  25096. this.blend = RenderState.BLEND_ENABLE_ALL;
  25097. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  25098. this.blendDst = RenderState.BLENDPARAM_ONE;
  25099. this.depthTest = RenderState.DEPTHTEST_LESS;
  25100. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_ADDTIVEFOG);
  25101. break;
  25102. case TrailMaterial.RENDERMODE_ALPHABLENDED:
  25103. this.renderQueue = BaseMaterial.RENDERQUEUE_TRANSPARENT;
  25104. this.alphaTest = false;
  25105. this.depthWrite = false;
  25106. this.cull = RenderState.CULL_NONE;
  25107. this.blend = RenderState.BLEND_ENABLE_ALL;
  25108. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  25109. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  25110. this.depthTest = RenderState.DEPTHTEST_LESS;
  25111. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_ADDTIVEFOG);
  25112. break;
  25113. default:
  25114. throw new Error("TrailMaterial : renderMode value error.");
  25115. }
  25116. }
  25117. get colorR() {
  25118. return this._TintColorR;
  25119. }
  25120. set colorR(value) {
  25121. this._TintColorR = value;
  25122. }
  25123. get colorG() {
  25124. return this._TintColorG;
  25125. }
  25126. set colorG(value) {
  25127. this._TintColorG = value;
  25128. }
  25129. get colorB() {
  25130. return this._TintColorB;
  25131. }
  25132. set colorB(value) {
  25133. this._TintColorB = value;
  25134. }
  25135. get colorA() {
  25136. return this._TintColorA;
  25137. }
  25138. set colorA(value) {
  25139. this._TintColorA = value;
  25140. }
  25141. get color() {
  25142. return this._shaderValues.getVector(TrailMaterial.TINTCOLOR);
  25143. }
  25144. set color(value) {
  25145. this._shaderValues.setVector(TrailMaterial.TINTCOLOR, value);
  25146. }
  25147. get texture() {
  25148. return this._shaderValues.getTexture(TrailMaterial.MAINTEXTURE);
  25149. }
  25150. set texture(value) {
  25151. if (value)
  25152. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_MAINTEXTURE);
  25153. else
  25154. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_MAINTEXTURE);
  25155. this._shaderValues.setTexture(TrailMaterial.MAINTEXTURE, value);
  25156. }
  25157. get tilingOffsetX() {
  25158. return this._MainTex_STX;
  25159. }
  25160. set tilingOffsetX(x) {
  25161. this._MainTex_STX = x;
  25162. }
  25163. get tilingOffsetY() {
  25164. return this._MainTex_STY;
  25165. }
  25166. set tilingOffsetY(y) {
  25167. this._MainTex_STY = y;
  25168. }
  25169. get tilingOffsetZ() {
  25170. return this._MainTex_STZ;
  25171. }
  25172. set tilingOffsetZ(z) {
  25173. this._MainTex_STZ = z;
  25174. }
  25175. get tilingOffsetW() {
  25176. return this._MainTex_STW;
  25177. }
  25178. set tilingOffsetW(w) {
  25179. this._MainTex_STW = w;
  25180. }
  25181. get tilingOffset() {
  25182. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  25183. }
  25184. set tilingOffset(value) {
  25185. if (value) {
  25186. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  25187. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  25188. else
  25189. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  25190. }
  25191. else {
  25192. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  25193. }
  25194. this._shaderValues.setVector(TrailMaterial.TILINGOFFSET, value);
  25195. }
  25196. set depthWrite(value) {
  25197. this._shaderValues.setBool(TrailMaterial.DEPTH_WRITE, value);
  25198. }
  25199. get depthWrite() {
  25200. return this._shaderValues.getBool(TrailMaterial.DEPTH_WRITE);
  25201. }
  25202. set cull(value) {
  25203. this._shaderValues.setInt(TrailMaterial.CULL, value);
  25204. }
  25205. get cull() {
  25206. return this._shaderValues.getInt(TrailMaterial.CULL);
  25207. }
  25208. set blend(value) {
  25209. this._shaderValues.setInt(TrailMaterial.BLEND, value);
  25210. }
  25211. get blend() {
  25212. return this._shaderValues.getInt(TrailMaterial.BLEND);
  25213. }
  25214. set blendSrc(value) {
  25215. this._shaderValues.setInt(TrailMaterial.BLEND_SRC, value);
  25216. }
  25217. get blendSrc() {
  25218. return this._shaderValues.getInt(TrailMaterial.BLEND_SRC);
  25219. }
  25220. set blendDst(value) {
  25221. this._shaderValues.setInt(TrailMaterial.BLEND_DST, value);
  25222. }
  25223. get blendDst() {
  25224. return this._shaderValues.getInt(TrailMaterial.BLEND_DST);
  25225. }
  25226. set depthTest(value) {
  25227. this._shaderValues.setInt(TrailMaterial.DEPTH_TEST, value);
  25228. }
  25229. get depthTest() {
  25230. return this._shaderValues.getInt(TrailMaterial.DEPTH_TEST);
  25231. }
  25232. clone() {
  25233. var dest = new TrailMaterial();
  25234. this.cloneTo(dest);
  25235. return dest;
  25236. }
  25237. }
  25238. TrailMaterial.RENDERMODE_ALPHABLENDED = 0;
  25239. TrailMaterial.RENDERMODE_ADDTIVE = 1;
  25240. TrailMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_MainTexture");
  25241. TrailMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_MainColor");
  25242. TrailMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  25243. TrailMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  25244. TrailMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  25245. TrailMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  25246. TrailMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  25247. TrailMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  25248. TrailMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  25249. class TextureMode {
  25250. }
  25251. TextureMode.Stretch = 0;
  25252. TextureMode.Tile = 1;
  25253. (function (TrailAlignment) {
  25254. TrailAlignment[TrailAlignment["View"] = 0] = "View";
  25255. TrailAlignment[TrailAlignment["TransformZ"] = 1] = "TransformZ";
  25256. })(exports.TrailAlignment || (exports.TrailAlignment = {}));
  25257. class VertexTrail {
  25258. constructor() {
  25259. }
  25260. static get vertexDeclaration1() {
  25261. return VertexTrail._vertexDeclaration1;
  25262. }
  25263. static get vertexDeclaration2() {
  25264. return VertexTrail._vertexDeclaration2;
  25265. }
  25266. get vertexDeclaration() {
  25267. return VertexTrail._vertexDeclaration1;
  25268. }
  25269. static __init__() {
  25270. VertexTrail._vertexDeclaration1 = new VertexDeclaration(32, [new VertexElement(0, VertexElementFormat.Vector3, VertexTrail.TRAIL_POSITION0),
  25271. new VertexElement(12, VertexElementFormat.Vector3, VertexTrail.TRAIL_OFFSETVECTOR),
  25272. new VertexElement(24, VertexElementFormat.Single, VertexTrail.TRAIL_TIME0),
  25273. new VertexElement(28, VertexElementFormat.Single, VertexTrail.TRAIL_TEXTURECOORDINATE0Y)]);
  25274. VertexTrail._vertexDeclaration2 = new VertexDeclaration(20, [new VertexElement(0, VertexElementFormat.Single, VertexTrail.TRAIL_TEXTURECOORDINATE0X),
  25275. new VertexElement(4, VertexElementFormat.Color, VertexTrail.TRAIL_COLOR)]);
  25276. }
  25277. }
  25278. VertexTrail.TRAIL_POSITION0 = 0;
  25279. VertexTrail.TRAIL_OFFSETVECTOR = 1;
  25280. VertexTrail.TRAIL_TIME0 = 2;
  25281. VertexTrail.TRAIL_TEXTURECOORDINATE0Y = 3;
  25282. VertexTrail.TRAIL_TEXTURECOORDINATE0X = 4;
  25283. VertexTrail.TRAIL_COLOR = 5;
  25284. class TrailGeometry extends GeometryElement {
  25285. constructor(owner) {
  25286. super();
  25287. this._floatCountPerVertices1 = 8;
  25288. this._floatCountPerVertices2 = 5;
  25289. this._increaseSegementCount = 16;
  25290. this._activeIndex = 0;
  25291. this._endIndex = 0;
  25292. this._needAddFirstVertex = false;
  25293. this._isTempEndVertex = false;
  25294. this._vertices1 = null;
  25295. this._vertices2 = null;
  25296. this._lastFixedVertexPosition = new Vector3();
  25297. this._bufferState = new BufferState();
  25298. this.tmpColor = new Color();
  25299. this._disappearBoundsMode = false;
  25300. this._owner = owner;
  25301. this._segementCount = this._increaseSegementCount;
  25302. this._resizeData(this._segementCount, this._bufferState);
  25303. var bounds = this._owner._owner.trailRenderer.bounds;
  25304. var sprite3dPosition = this._owner._owner.transform.position;
  25305. bounds.setMin(sprite3dPosition);
  25306. bounds.setMax(sprite3dPosition);
  25307. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  25308. }
  25309. _resizeData(segementCount, bufferState) {
  25310. this._subBirthTime = new Float32Array(segementCount);
  25311. this._subDistance = new Float64Array(segementCount);
  25312. var gl = Laya.LayaGL.instance;
  25313. var vertexCount = segementCount * 2;
  25314. var vertexDeclaration1 = VertexTrail.vertexDeclaration1;
  25315. var vertexDeclaration2 = VertexTrail.vertexDeclaration2;
  25316. var vertexBuffers = [];
  25317. var vertexbuffer1Size = vertexCount * vertexDeclaration1.vertexStride;
  25318. var vertexbuffer2Size = vertexCount * vertexDeclaration2.vertexStride;
  25319. var memorySize = vertexbuffer1Size + vertexbuffer2Size;
  25320. this._vertices1 = new Float32Array(vertexCount * this._floatCountPerVertices1);
  25321. this._vertices2 = new Float32Array(vertexCount * this._floatCountPerVertices2);
  25322. this._vertexBuffer1 = new VertexBuffer3D(vertexbuffer1Size, gl.STATIC_DRAW, false);
  25323. this._vertexBuffer1.vertexDeclaration = vertexDeclaration1;
  25324. this._vertexBuffer2 = new VertexBuffer3D(vertexbuffer2Size, gl.DYNAMIC_DRAW, false);
  25325. this._vertexBuffer2.vertexDeclaration = vertexDeclaration2;
  25326. vertexBuffers.push(this._vertexBuffer1);
  25327. vertexBuffers.push(this._vertexBuffer2);
  25328. bufferState.bind();
  25329. bufferState.applyVertexBuffers(vertexBuffers);
  25330. bufferState.unBind();
  25331. Laya.Resource._addMemory(memorySize, memorySize);
  25332. }
  25333. _resetData() {
  25334. var count = this._endIndex - this._activeIndex;
  25335. var oldVertices1 = new Float32Array(this._vertices1.buffer, this._floatCountPerVertices1 * 2 * this._activeIndex * 4, this._floatCountPerVertices1 * 2 * count);
  25336. var oldVertices2 = new Float32Array(this._vertices2.buffer, this._floatCountPerVertices2 * 2 * this._activeIndex * 4, this._floatCountPerVertices2 * 2 * count);
  25337. var oldSubDistance = new Float64Array(this._subDistance.buffer, this._activeIndex * 8, count);
  25338. var oldSubBirthTime = new Float32Array(this._subBirthTime.buffer, this._activeIndex * 4, count);
  25339. if (count === this._segementCount) {
  25340. this._vertexBuffer1.destroy();
  25341. this._vertexBuffer2.destroy();
  25342. this._segementCount += this._increaseSegementCount;
  25343. this._resizeData(this._segementCount, this._bufferState);
  25344. }
  25345. this._vertices1.set(oldVertices1, 0);
  25346. this._vertices2.set(oldVertices2, 0);
  25347. this._subDistance.set(oldSubDistance, 0);
  25348. this._subBirthTime.set(oldSubBirthTime, 0);
  25349. this._endIndex = count;
  25350. this._activeIndex = 0;
  25351. this._vertexBuffer1.setData(this._vertices1.buffer, 0, this._floatCountPerVertices1 * 2 * this._activeIndex * 4, this._floatCountPerVertices1 * 2 * count * 4);
  25352. this._vertexBuffer2.setData(this._vertices2.buffer, 0, this._floatCountPerVertices2 * 2 * this._activeIndex * 4, this._floatCountPerVertices2 * 2 * count * 4);
  25353. }
  25354. _updateTrail(camera, lastPosition, position) {
  25355. if (!Vector3.equals(lastPosition, position)) {
  25356. if ((this._endIndex - this._activeIndex) === 0)
  25357. this._addTrailByFirstPosition(camera, position);
  25358. else
  25359. this._addTrailByNextPosition(camera, position);
  25360. }
  25361. }
  25362. _addTrailByFirstPosition(camera, position) {
  25363. (this._endIndex === this._segementCount) && (this._resetData());
  25364. this._subDistance[this._endIndex] = 0;
  25365. this._subBirthTime[this._endIndex] = this._owner._curtime;
  25366. this._endIndex++;
  25367. position.cloneTo(this._lastFixedVertexPosition);
  25368. this._needAddFirstVertex = true;
  25369. }
  25370. _addTrailByNextPosition(camera, position) {
  25371. var delVector3 = TrailGeometry._tempVector30;
  25372. var pointAtoBVector3 = TrailGeometry._tempVector31;
  25373. switch (this._owner.alignment) {
  25374. case exports.TrailAlignment.View:
  25375. var cameraMatrix = camera.viewMatrix;
  25376. Vector3.transformCoordinate(position, cameraMatrix, TrailGeometry._tempVector33);
  25377. Vector3.transformCoordinate(this._lastFixedVertexPosition, cameraMatrix, TrailGeometry._tempVector34);
  25378. Vector3.subtract(TrailGeometry._tempVector33, TrailGeometry._tempVector34, delVector3);
  25379. Vector3.cross(TrailGeometry._tempVector33, delVector3, pointAtoBVector3);
  25380. break;
  25381. case exports.TrailAlignment.TransformZ:
  25382. Vector3.subtract(position, this._lastFixedVertexPosition, delVector3);
  25383. var forward = TrailGeometry._tempVector32;
  25384. this._owner._owner.transform.localMatrix.getForward(forward);
  25385. Vector3.cross(delVector3, forward, pointAtoBVector3);
  25386. break;
  25387. }
  25388. Vector3.normalize(pointAtoBVector3, pointAtoBVector3);
  25389. Vector3.scale(pointAtoBVector3, this._owner.widthMultiplier / 2, pointAtoBVector3);
  25390. var delLength = Vector3.scalarLength(delVector3);
  25391. var tempEndIndex;
  25392. var offset;
  25393. if (this._needAddFirstVertex) {
  25394. this._updateVerticesByPositionData(position, pointAtoBVector3, this._endIndex - 1);
  25395. this._needAddFirstVertex = false;
  25396. }
  25397. if (delLength - this._owner.minVertexDistance >= MathUtils3D.zeroTolerance) {
  25398. if (this._isTempEndVertex) {
  25399. tempEndIndex = this._endIndex - 1;
  25400. offset = delLength - this._subDistance[tempEndIndex];
  25401. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, tempEndIndex);
  25402. this._owner._totalLength += offset;
  25403. }
  25404. else {
  25405. (this._endIndex === this._segementCount) && (this._resetData());
  25406. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, this._endIndex);
  25407. this._owner._totalLength += delLength;
  25408. this._endIndex++;
  25409. }
  25410. position.cloneTo(this._lastFixedVertexPosition);
  25411. this._isTempEndVertex = false;
  25412. }
  25413. else {
  25414. if (this._isTempEndVertex) {
  25415. tempEndIndex = this._endIndex - 1;
  25416. offset = delLength - this._subDistance[tempEndIndex];
  25417. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, tempEndIndex);
  25418. this._owner._totalLength += offset;
  25419. }
  25420. else {
  25421. (this._endIndex === this._segementCount) && (this._resetData());
  25422. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, this._endIndex);
  25423. this._owner._totalLength += delLength;
  25424. this._endIndex++;
  25425. }
  25426. this._isTempEndVertex = true;
  25427. }
  25428. }
  25429. _updateVerticesByPositionData(position, pointAtoBVector3, index) {
  25430. var vertexOffset = this._floatCountPerVertices1 * 2 * index;
  25431. var curtime = this._owner._curtime;
  25432. this._vertices1[vertexOffset] = position.x;
  25433. this._vertices1[vertexOffset + 1] = position.y;
  25434. this._vertices1[vertexOffset + 2] = position.z;
  25435. this._vertices1[vertexOffset + 3] = -pointAtoBVector3.x;
  25436. this._vertices1[vertexOffset + 4] = -pointAtoBVector3.y;
  25437. this._vertices1[vertexOffset + 5] = -pointAtoBVector3.z;
  25438. this._vertices1[vertexOffset + 6] = curtime;
  25439. this._vertices1[vertexOffset + 7] = 1.0;
  25440. this._vertices1[vertexOffset + 8] = position.x;
  25441. this._vertices1[vertexOffset + 9] = position.y;
  25442. this._vertices1[vertexOffset + 10] = position.z;
  25443. this._vertices1[vertexOffset + 11] = pointAtoBVector3.x;
  25444. this._vertices1[vertexOffset + 12] = pointAtoBVector3.y;
  25445. this._vertices1[vertexOffset + 13] = pointAtoBVector3.z;
  25446. this._vertices1[vertexOffset + 14] = curtime;
  25447. this._vertices1[vertexOffset + 15] = 0.0;
  25448. var bounds = this._owner._owner.trailRenderer.bounds;
  25449. var min = bounds.getMin();
  25450. var max = bounds.getMax();
  25451. var up = TrailGeometry._tempVector35;
  25452. var down = TrailGeometry._tempVector36;
  25453. var out = TrailGeometry._tempVector32;
  25454. Vector3.add(position, pointAtoBVector3, up);
  25455. Vector3.subtract(position, pointAtoBVector3, down);
  25456. Vector3.min(down, up, out);
  25457. Vector3.min(min, out, min);
  25458. bounds.setMin(min);
  25459. Vector3.max(up, down, out);
  25460. Vector3.max(max, out, max);
  25461. bounds.setMax(max);
  25462. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  25463. var floatCount = this._floatCountPerVertices1 * 2;
  25464. this._vertexBuffer1.setData(this._vertices1.buffer, vertexOffset * 4, vertexOffset * 4, floatCount * 4);
  25465. }
  25466. _updateVerticesByPosition(position, pointAtoBVector3, delDistance, index) {
  25467. this._updateVerticesByPositionData(position, pointAtoBVector3, index);
  25468. this._subDistance[index] = delDistance;
  25469. this._subBirthTime[index] = this._owner._curtime;
  25470. }
  25471. _updateVertexBufferUV() {
  25472. var bounds;
  25473. var min, max;
  25474. if (this._disappearBoundsMode) {
  25475. bounds = this._owner._owner.trailRenderer.bounds;
  25476. min = bounds.getMin();
  25477. max = bounds.getMax();
  25478. min.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25479. max.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25480. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  25481. }
  25482. var vertexCount = this._endIndex;
  25483. var curLength = 0;
  25484. var gradient = this._owner.colorGradient;
  25485. var startAlphaIndex = gradient.colorAlphaKeysCount - 1;
  25486. var startColorIndex = gradient.colorRGBKeysCount - 1;
  25487. var totalLength = this._owner._totalLength;
  25488. var stride = this._floatCountPerVertices2 * 2;
  25489. for (var i = this._activeIndex; i < vertexCount; i++) {
  25490. (i !== this._activeIndex) && (curLength += this._subDistance[i]);
  25491. var uvX;
  25492. var lerpFactor;
  25493. if (this._owner.textureMode == TextureMode.Stretch) {
  25494. uvX = 1.0 - curLength / totalLength;
  25495. lerpFactor = uvX;
  25496. }
  25497. else {
  25498. lerpFactor = 1.0 - curLength / totalLength;
  25499. uvX = 1.0 - (totalLength - curLength);
  25500. }
  25501. startColorIndex = gradient.evaluateColorRGB(lerpFactor, this.tmpColor, startColorIndex, true);
  25502. startAlphaIndex = gradient.evaluateColorAlpha(lerpFactor, this.tmpColor, startAlphaIndex, true);
  25503. var index = i * stride;
  25504. this._vertices2[index + 0] = uvX;
  25505. this._vertices2[index + 1] = this.tmpColor.r;
  25506. this._vertices2[index + 2] = this.tmpColor.g;
  25507. this._vertices2[index + 3] = this.tmpColor.b;
  25508. this._vertices2[index + 4] = this.tmpColor.a;
  25509. this._vertices2[index + 5] = uvX;
  25510. this._vertices2[index + 6] = this.tmpColor.r;
  25511. this._vertices2[index + 7] = this.tmpColor.g;
  25512. this._vertices2[index + 8] = this.tmpColor.b;
  25513. this._vertices2[index + 9] = this.tmpColor.a;
  25514. if (this._disappearBoundsMode) {
  25515. var posOffset = this._floatCountPerVertices1 * 2 * i;
  25516. var pos = TrailGeometry._tempVector32;
  25517. var up = TrailGeometry._tempVector33;
  25518. var side = TrailGeometry._tempVector34;
  25519. pos.setValue(this._vertices1[posOffset + 0], this._vertices1[posOffset + 1], this._vertices1[posOffset + 2]);
  25520. up.setValue(this._vertices1[posOffset + 3], this._vertices1[posOffset + 4], this._vertices1[posOffset + 5]);
  25521. Vector3.add(pos, up, side);
  25522. Vector3.min(side, min, min);
  25523. Vector3.max(side, max, max);
  25524. Vector3.subtract(pos, up, side);
  25525. Vector3.min(side, min, min);
  25526. Vector3.max(side, max, max);
  25527. }
  25528. }
  25529. if (this._disappearBoundsMode) {
  25530. bounds.setMin(min);
  25531. bounds.setMax(max);
  25532. this._disappearBoundsMode = false;
  25533. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  25534. }
  25535. var offset = this._activeIndex * stride;
  25536. this._vertexBuffer2.setData(this._vertices2.buffer, offset * 4, offset * 4, (vertexCount * stride - offset) * 4);
  25537. }
  25538. _updateDisappear() {
  25539. var count = this._endIndex;
  25540. for (var i = this._activeIndex; i < count; i++) {
  25541. if (this._owner._curtime - this._subBirthTime[i] >= this._owner.time + MathUtils3D.zeroTolerance) {
  25542. var nextIndex = i + 1;
  25543. if (nextIndex !== count)
  25544. this._owner._totalLength -= this._subDistance[nextIndex];
  25545. if (this._isTempEndVertex && (nextIndex === count - 1)) {
  25546. var offset = this._floatCountPerVertices1 * i * 2;
  25547. var fixedPos = this._lastFixedVertexPosition;
  25548. fixedPos.x = this._vertices1[0];
  25549. fixedPos.y = this._vertices1[1];
  25550. fixedPos.z = this._vertices1[2];
  25551. this._isTempEndVertex = false;
  25552. }
  25553. this._activeIndex++;
  25554. this._disappearBoundsMode = true;
  25555. }
  25556. else {
  25557. break;
  25558. }
  25559. }
  25560. }
  25561. _getType() {
  25562. return TrailGeometry._type;
  25563. }
  25564. _prepareRender(state) {
  25565. return this._endIndex - this._activeIndex > 1;
  25566. }
  25567. _render(state) {
  25568. this._bufferState.bind();
  25569. var gl = Laya.LayaGL.instance;
  25570. var start = this._activeIndex * 2;
  25571. var count = this._endIndex * 2 - start;
  25572. gl.drawArrays(gl.TRIANGLE_STRIP, start, count);
  25573. Laya.Stat.renderBatches++;
  25574. Laya.Stat.trianglesFaces += count - 2;
  25575. }
  25576. destroy() {
  25577. super.destroy();
  25578. var memorySize = this._vertexBuffer1._byteLength + this._vertexBuffer2._byteLength;
  25579. Laya.Resource._addMemory(-memorySize, -memorySize);
  25580. this._bufferState.destroy();
  25581. this._vertexBuffer1.destroy();
  25582. this._vertexBuffer2.destroy();
  25583. this._bufferState = null;
  25584. this._vertices1 = null;
  25585. this._vertexBuffer1 = null;
  25586. this._vertices2 = null;
  25587. this._vertexBuffer2 = null;
  25588. this._subBirthTime = null;
  25589. this._subDistance = null;
  25590. this._lastFixedVertexPosition = null;
  25591. this._disappearBoundsMode = false;
  25592. }
  25593. _calculateBoundingBoxForNative() {
  25594. var trail = this._owner._owner.trailRenderer;
  25595. var bounds = trail.bounds;
  25596. var min = bounds.getMin();
  25597. var max = bounds.getMax();
  25598. var buffer = FrustumCulling._cullingBuffer;
  25599. buffer[trail._cullingBufferIndex + 1] = min.x;
  25600. buffer[trail._cullingBufferIndex + 2] = min.y;
  25601. buffer[trail._cullingBufferIndex + 3] = min.z;
  25602. buffer[trail._cullingBufferIndex + 4] = max.x;
  25603. buffer[trail._cullingBufferIndex + 5] = max.y;
  25604. buffer[trail._cullingBufferIndex + 6] = max.z;
  25605. }
  25606. }
  25607. TrailGeometry.ALIGNMENT_VIEW = 0;
  25608. TrailGeometry.ALIGNMENT_TRANSFORM_Z = 1;
  25609. TrailGeometry._tempVector30 = new Vector3();
  25610. TrailGeometry._tempVector31 = new Vector3();
  25611. TrailGeometry._tempVector32 = new Vector3();
  25612. TrailGeometry._tempVector33 = new Vector3();
  25613. TrailGeometry._tempVector34 = new Vector3();
  25614. TrailGeometry._tempVector35 = new Vector3();
  25615. TrailGeometry._tempVector36 = new Vector3();
  25616. TrailGeometry._type = GeometryElement._typeCounter++;
  25617. class TrailFilter {
  25618. constructor(owner) {
  25619. this._totalLength = 0;
  25620. this._lastPosition = new Vector3();
  25621. this._curtime = 0;
  25622. this.alignment = TrailFilter.ALIGNMENT_VIEW;
  25623. this._owner = owner;
  25624. this._initDefaultData();
  25625. this.addRenderElement();
  25626. }
  25627. get time() {
  25628. return this._time;
  25629. }
  25630. set time(value) {
  25631. this._time = value;
  25632. this._owner._render._shaderValues.setNumber(TrailFilter.LIFETIME, value);
  25633. }
  25634. get minVertexDistance() {
  25635. return this._minVertexDistance;
  25636. }
  25637. set minVertexDistance(value) {
  25638. this._minVertexDistance = value;
  25639. }
  25640. get widthMultiplier() {
  25641. return this._widthMultiplier;
  25642. }
  25643. set widthMultiplier(value) {
  25644. this._widthMultiplier = value;
  25645. }
  25646. get widthCurve() {
  25647. return this._widthCurve;
  25648. }
  25649. set widthCurve(value) {
  25650. this._widthCurve = value;
  25651. var widthCurveFloatArray = new Float32Array(value.length * 4);
  25652. var i, j, index = 0;
  25653. for (i = 0, j = value.length; i < j; i++) {
  25654. widthCurveFloatArray[index++] = value[i].time;
  25655. widthCurveFloatArray[index++] = value[i].inTangent;
  25656. widthCurveFloatArray[index++] = value[i].outTangent;
  25657. widthCurveFloatArray[index++] = value[i].value;
  25658. }
  25659. this._owner._render._shaderValues.setBuffer(TrailFilter.WIDTHCURVE, widthCurveFloatArray);
  25660. this._owner._render._shaderValues.setInt(TrailFilter.WIDTHCURVEKEYLENGTH, value.length);
  25661. }
  25662. get colorGradient() {
  25663. return this._colorGradient;
  25664. }
  25665. set colorGradient(value) {
  25666. this._colorGradient = value;
  25667. }
  25668. get textureMode() {
  25669. return this._textureMode;
  25670. }
  25671. set textureMode(value) {
  25672. this._textureMode = value;
  25673. }
  25674. addRenderElement() {
  25675. var render = this._owner._render;
  25676. var elements = render._renderElements;
  25677. var material = render.sharedMaterials[0];
  25678. (material) || (material = TrailMaterial.defaultMaterial);
  25679. var element = new RenderElement();
  25680. element.setTransform(this._owner._transform);
  25681. element.render = render;
  25682. element.material = material;
  25683. this._trialGeometry = new TrailGeometry(this);
  25684. element.setGeometry(this._trialGeometry);
  25685. elements.push(element);
  25686. }
  25687. _update(state) {
  25688. var render = this._owner._render;
  25689. this._curtime += state.scene.timer._delta / 1000;
  25690. render._shaderValues.setNumber(TrailFilter.CURTIME, this._curtime);
  25691. var curPos = this._owner.transform.position;
  25692. var element = render._renderElements[0]._geometry;
  25693. element._updateDisappear();
  25694. element._updateTrail(state.camera, this._lastPosition, curPos);
  25695. element._updateVertexBufferUV();
  25696. curPos.cloneTo(this._lastPosition);
  25697. }
  25698. _initDefaultData() {
  25699. this.time = 5.0;
  25700. this.minVertexDistance = 0.1;
  25701. this.widthMultiplier = 1;
  25702. this.textureMode = TextureMode.Stretch;
  25703. var widthKeyFrames = [];
  25704. var widthKeyFrame1 = new FloatKeyframe();
  25705. widthKeyFrame1.time = 0;
  25706. widthKeyFrame1.inTangent = 0;
  25707. widthKeyFrame1.outTangent = 0;
  25708. widthKeyFrame1.value = 1;
  25709. widthKeyFrames.push(widthKeyFrame1);
  25710. var widthKeyFrame2 = new FloatKeyframe();
  25711. widthKeyFrame2.time = 1;
  25712. widthKeyFrame2.inTangent = 0;
  25713. widthKeyFrame2.outTangent = 0;
  25714. widthKeyFrame2.value = 1;
  25715. widthKeyFrames.push(widthKeyFrame2);
  25716. this.widthCurve = widthKeyFrames;
  25717. var gradient = new Gradient(2, 2);
  25718. gradient.mode = GradientMode.Blend;
  25719. gradient.addColorRGB(0, Color.WHITE);
  25720. gradient.addColorRGB(1, Color.WHITE);
  25721. gradient.addColorAlpha(0, 1);
  25722. gradient.addColorAlpha(1, 1);
  25723. this.colorGradient = gradient;
  25724. }
  25725. destroy() {
  25726. this._trialGeometry.destroy();
  25727. this._trialGeometry = null;
  25728. this._widthCurve = null;
  25729. this._colorGradient = null;
  25730. }
  25731. }
  25732. TrailFilter.CURTIME = Shader3D.propertyNameToID("u_CurTime");
  25733. TrailFilter.LIFETIME = Shader3D.propertyNameToID("u_LifeTime");
  25734. TrailFilter.WIDTHCURVE = Shader3D.propertyNameToID("u_WidthCurve");
  25735. TrailFilter.WIDTHCURVEKEYLENGTH = Shader3D.propertyNameToID("u_WidthCurveKeyLength");
  25736. TrailFilter.ALIGNMENT_VIEW = 0;
  25737. TrailFilter.ALIGNMENT_TRANSFORM_Z = 1;
  25738. class TrailRenderer extends BaseRender {
  25739. constructor(owner) {
  25740. super(owner);
  25741. this._projectionViewWorldMatrix = new Matrix4x4();
  25742. }
  25743. _calculateBoundingBox() {
  25744. }
  25745. _needRender(boundFrustum, context) {
  25746. this._owner.trailFilter._update(context);
  25747. if (boundFrustum)
  25748. return boundFrustum.intersects(this.bounds._getBoundBox());
  25749. else
  25750. return true;
  25751. }
  25752. _updateForNative(context) {
  25753. this._owner.trailFilter._update(context);
  25754. }
  25755. _renderUpdate(state, transform) {
  25756. super._renderUpdate(state, transform);
  25757. }
  25758. _renderUpdateWithCamera(context, transform) {
  25759. var projectionView = context.projectionViewMatrix;
  25760. if (transform) {
  25761. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  25762. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  25763. }
  25764. else {
  25765. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  25766. }
  25767. }
  25768. }
  25769. class TrailSprite3D extends RenderableSprite3D {
  25770. static __init__() {
  25771. }
  25772. get trailFilter() {
  25773. return this._geometryFilter;
  25774. }
  25775. get trailRenderer() {
  25776. return this._render;
  25777. }
  25778. constructor(name = null) {
  25779. super(name);
  25780. this._render = new TrailRenderer(this);
  25781. this._geometryFilter = new TrailFilter(this);
  25782. }
  25783. _parse(data, spriteMap) {
  25784. super._parse(data, spriteMap);
  25785. var render = this._render;
  25786. var filter = this._geometryFilter;
  25787. var i, j;
  25788. var materials = data.materials;
  25789. if (materials) {
  25790. var sharedMaterials = render.sharedMaterials;
  25791. var materialCount = materials.length;
  25792. sharedMaterials.length = materialCount;
  25793. for (i = 0; i < materialCount; i++)
  25794. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  25795. render.sharedMaterials = sharedMaterials;
  25796. }
  25797. filter.time = data.time;
  25798. filter.minVertexDistance = data.minVertexDistance;
  25799. filter.widthMultiplier = data.widthMultiplier;
  25800. filter.textureMode = data.textureMode;
  25801. (data.alignment != null) && (filter.alignment = data.alignment);
  25802. var widthCurve = [];
  25803. var widthCurveData = data.widthCurve;
  25804. for (i = 0, j = widthCurveData.length; i < j; i++) {
  25805. var trailkeyframe = new FloatKeyframe();
  25806. trailkeyframe.time = widthCurveData[i].time;
  25807. trailkeyframe.inTangent = widthCurveData[i].inTangent;
  25808. trailkeyframe.outTangent = widthCurveData[i].outTangent;
  25809. trailkeyframe.value = widthCurveData[i].value;
  25810. widthCurve.push(trailkeyframe);
  25811. }
  25812. filter.widthCurve = widthCurve;
  25813. var colorGradientData = data.colorGradient;
  25814. var colorKeys = colorGradientData.colorKeys;
  25815. var alphaKeys = colorGradientData.alphaKeys;
  25816. var colorGradient = new Gradient(colorKeys.length, alphaKeys.length);
  25817. colorGradient.mode = colorGradientData.mode;
  25818. for (i = 0, j = colorKeys.length; i < j; i++) {
  25819. var colorKey = colorKeys[i];
  25820. colorGradient.addColorRGB(colorKey.time, new Color(colorKey.value[0], colorKey.value[1], colorKey.value[2], 1.0));
  25821. }
  25822. for (i = 0, j = alphaKeys.length; i < j; i++) {
  25823. var alphaKey = alphaKeys[i];
  25824. colorGradient.addColorAlpha(alphaKey.time, alphaKey.value);
  25825. }
  25826. filter.colorGradient = colorGradient;
  25827. }
  25828. _onActive() {
  25829. super._onActive();
  25830. this._transform.position.cloneTo(this._geometryFilter._lastPosition);
  25831. }
  25832. _cloneTo(destObject, srcSprite, dstSprite) {
  25833. super._cloneTo(destObject, srcSprite, dstSprite);
  25834. var i, j;
  25835. var destTrailSprite3D = destObject;
  25836. var destTrailFilter = destTrailSprite3D.trailFilter;
  25837. destTrailFilter.time = this.trailFilter.time;
  25838. destTrailFilter.minVertexDistance = this.trailFilter.minVertexDistance;
  25839. destTrailFilter.widthMultiplier = this.trailFilter.widthMultiplier;
  25840. destTrailFilter.textureMode = this.trailFilter.textureMode;
  25841. destTrailFilter.alignment = this.trailFilter.alignment;
  25842. var widthCurveData = this.trailFilter.widthCurve;
  25843. var widthCurve = [];
  25844. for (i = 0, j = widthCurveData.length; i < j; i++) {
  25845. var keyFrame = new FloatKeyframe();
  25846. widthCurveData[i].cloneTo(keyFrame);
  25847. widthCurve.push(keyFrame);
  25848. }
  25849. destTrailFilter.widthCurve = widthCurve;
  25850. var destColorGradient = new Gradient(this.trailFilter.colorGradient.maxColorRGBKeysCount, this.trailFilter.colorGradient.maxColorAlphaKeysCount);
  25851. this.trailFilter.colorGradient.cloneTo(destColorGradient);
  25852. destTrailFilter.colorGradient = destColorGradient;
  25853. var destTrailRender = destTrailSprite3D.trailRenderer;
  25854. destTrailRender.sharedMaterial = this.trailRenderer.sharedMaterial;
  25855. }
  25856. destroy(destroyChild = true) {
  25857. if (this.destroyed)
  25858. return;
  25859. super.destroy(destroyChild);
  25860. this._geometryFilter.destroy();
  25861. this._geometryFilter = null;
  25862. }
  25863. _create() {
  25864. return new TrailSprite3D();
  25865. }
  25866. }
  25867. class VertexPositionTerrain {
  25868. constructor(position, normal, textureCoord0, textureCoord1) {
  25869. this._position = position;
  25870. this._normal = normal;
  25871. this._textureCoord0 = textureCoord0;
  25872. this._textureCoord1 = textureCoord1;
  25873. }
  25874. static __init__() {
  25875. VertexPositionTerrain._vertexDeclaration = new VertexDeclaration(40, [new VertexElement(0, VertexElementFormat.Vector3, VertexPositionTerrain.TERRAIN_POSITION0),
  25876. new VertexElement(12, VertexElementFormat.Vector3, VertexPositionTerrain.TERRAIN_NORMAL0),
  25877. new VertexElement(24, VertexElementFormat.Vector2, VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE0),
  25878. new VertexElement(32, VertexElementFormat.Vector2, VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE1)]);
  25879. }
  25880. static get vertexDeclaration() {
  25881. return VertexPositionTerrain._vertexDeclaration;
  25882. }
  25883. get position() {
  25884. return this._position;
  25885. }
  25886. get normal() {
  25887. return this._normal;
  25888. }
  25889. get textureCoord0() {
  25890. return this._textureCoord0;
  25891. }
  25892. get textureCoord1() {
  25893. return this._textureCoord1;
  25894. }
  25895. get vertexDeclaration() {
  25896. return VertexPositionTerrain._vertexDeclaration;
  25897. }
  25898. }
  25899. VertexPositionTerrain.TERRAIN_POSITION0 = 0;
  25900. VertexPositionTerrain.TERRAIN_NORMAL0 = 1;
  25901. VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE0 = 2;
  25902. VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE1 = 3;
  25903. class CharacterController extends PhysicsComponent {
  25904. constructor(stepheight = 0.1, upAxis = null, collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  25905. super(collisionGroup, canCollideWith);
  25906. this._upAxis = new Vector3(0, 1, 0);
  25907. this._maxSlope = 45.0;
  25908. this._jumpSpeed = 10.0;
  25909. this._fallSpeed = 55.0;
  25910. this._gravity = new Vector3(0, -9.8 * 3, 0);
  25911. this._nativeKinematicCharacter = null;
  25912. this._stepHeight = stepheight;
  25913. (upAxis) && (this._upAxis = upAxis);
  25914. }
  25915. static __init__() {
  25916. CharacterController._nativeTempVector30 = new Physics3D._physics3D.btVector3(0, 0, 0);
  25917. }
  25918. get fallSpeed() {
  25919. return this._fallSpeed;
  25920. }
  25921. set fallSpeed(value) {
  25922. this._fallSpeed = value;
  25923. this._nativeKinematicCharacter.setFallSpeed(value);
  25924. }
  25925. get jumpSpeed() {
  25926. return this._jumpSpeed;
  25927. }
  25928. set jumpSpeed(value) {
  25929. this._jumpSpeed = value;
  25930. this._nativeKinematicCharacter.setJumpSpeed(value);
  25931. }
  25932. get gravity() {
  25933. return this._gravity;
  25934. }
  25935. set gravity(value) {
  25936. this._gravity = value;
  25937. var nativeGravity = CharacterController._nativeTempVector30;
  25938. nativeGravity.setValue(-value.x, value.y, value.z);
  25939. this._nativeKinematicCharacter.setGravity(nativeGravity);
  25940. }
  25941. get maxSlope() {
  25942. return this._maxSlope;
  25943. }
  25944. set maxSlope(value) {
  25945. this._maxSlope = value;
  25946. this._nativeKinematicCharacter.setMaxSlope((value / 180) * Math.PI);
  25947. }
  25948. get isGrounded() {
  25949. return this._nativeKinematicCharacter.onGround();
  25950. }
  25951. get stepHeight() {
  25952. return this._stepHeight;
  25953. }
  25954. set stepHeight(value) {
  25955. this._stepHeight = value;
  25956. this._constructCharacter();
  25957. }
  25958. get upAxis() {
  25959. return this._upAxis;
  25960. }
  25961. set upAxis(value) {
  25962. this._upAxis = value;
  25963. this._constructCharacter();
  25964. }
  25965. _constructCharacter() {
  25966. var physics3D = Physics3D._physics3D;
  25967. if (this._nativeKinematicCharacter)
  25968. physics3D.destroy(this._nativeKinematicCharacter);
  25969. var nativeUpAxis = CharacterController._nativeTempVector30;
  25970. nativeUpAxis.setValue(this._upAxis.x, this._upAxis.y, this._upAxis.z);
  25971. this._nativeKinematicCharacter = new physics3D.btKinematicCharacterController(this._nativeColliderObject, this._colliderShape._nativeShape, this._stepHeight, nativeUpAxis);
  25972. this.fallSpeed = this._fallSpeed;
  25973. this.maxSlope = this._maxSlope;
  25974. this.jumpSpeed = this._jumpSpeed;
  25975. this.gravity = this._gravity;
  25976. }
  25977. _onShapeChange(colShape) {
  25978. super._onShapeChange(colShape);
  25979. this._constructCharacter();
  25980. }
  25981. _onAdded() {
  25982. var physics3D = Physics3D._physics3D;
  25983. var ghostObject = new physics3D.btPairCachingGhostObject();
  25984. ghostObject.setUserIndex(this.id);
  25985. ghostObject.setCollisionFlags(PhysicsComponent.COLLISIONFLAGS_CHARACTER_OBJECT);
  25986. this._nativeColliderObject = ghostObject;
  25987. if (this._colliderShape)
  25988. this._constructCharacter();
  25989. super._onAdded();
  25990. }
  25991. _addToSimulation() {
  25992. this._simulation._characters.push(this);
  25993. this._simulation._addCharacter(this, this._collisionGroup, this._canCollideWith);
  25994. }
  25995. _removeFromSimulation() {
  25996. this._simulation._removeCharacter(this);
  25997. var characters = this._simulation._characters;
  25998. characters.splice(characters.indexOf(this), 1);
  25999. }
  26000. _cloneTo(dest) {
  26001. super._cloneTo(dest);
  26002. var destCharacterController = dest;
  26003. destCharacterController.stepHeight = this._stepHeight;
  26004. destCharacterController.upAxis = this._upAxis;
  26005. destCharacterController.maxSlope = this._maxSlope;
  26006. destCharacterController.jumpSpeed = this._jumpSpeed;
  26007. destCharacterController.fallSpeed = this._fallSpeed;
  26008. destCharacterController.gravity = this._gravity;
  26009. }
  26010. _onDestroy() {
  26011. Physics3D._physics3D.destroy(this._nativeKinematicCharacter);
  26012. super._onDestroy();
  26013. this._nativeKinematicCharacter = null;
  26014. }
  26015. move(movement) {
  26016. var nativeMovement = CharacterController._nativeVector30;
  26017. nativeMovement.setValue(-movement.x, movement.y, movement.z);
  26018. this._nativeKinematicCharacter.setWalkDirection(nativeMovement);
  26019. }
  26020. jump(velocity = null) {
  26021. if (velocity) {
  26022. var nativeVelocity = CharacterController._nativeVector30;
  26023. Utils3D._convertToBulletVec3(velocity, nativeVelocity, true);
  26024. this._nativeKinematicCharacter.jump(nativeVelocity);
  26025. }
  26026. else {
  26027. this._nativeKinematicCharacter.jump();
  26028. }
  26029. }
  26030. }
  26031. CharacterController.UPAXIS_X = 0;
  26032. CharacterController.UPAXIS_Y = 1;
  26033. CharacterController.UPAXIS_Z = 2;
  26034. class PhysicsTriggerComponent extends PhysicsComponent {
  26035. constructor(collisionGroup, canCollideWith) {
  26036. super(collisionGroup, canCollideWith);
  26037. this._isTrigger = false;
  26038. }
  26039. get isTrigger() {
  26040. return this._isTrigger;
  26041. }
  26042. set isTrigger(value) {
  26043. this._isTrigger = value;
  26044. if (this._nativeColliderObject) {
  26045. var flags = this._nativeColliderObject.getCollisionFlags();
  26046. if (value) {
  26047. if ((flags & PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE) === 0)
  26048. this._nativeColliderObject.setCollisionFlags(flags | PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE);
  26049. }
  26050. else {
  26051. if ((flags & PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE) !== 0)
  26052. this._nativeColliderObject.setCollisionFlags(flags ^ PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE);
  26053. }
  26054. }
  26055. }
  26056. _onAdded() {
  26057. super._onAdded();
  26058. this.isTrigger = this._isTrigger;
  26059. }
  26060. _cloneTo(dest) {
  26061. super._cloneTo(dest);
  26062. dest.isTrigger = this._isTrigger;
  26063. }
  26064. }
  26065. class PhysicsCollider extends PhysicsTriggerComponent {
  26066. constructor(collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  26067. super(collisionGroup, canCollideWith);
  26068. this._enableProcessCollisions = false;
  26069. }
  26070. _addToSimulation() {
  26071. this._simulation._addPhysicsCollider(this, this._collisionGroup, this._canCollideWith);
  26072. }
  26073. _removeFromSimulation() {
  26074. this._simulation._removePhysicsCollider(this);
  26075. }
  26076. _onTransformChanged(flag) {
  26077. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  26078. if (flag) {
  26079. this._transformFlag |= flag;
  26080. if (this._isValid() && this._inPhysicUpdateListIndex === -1)
  26081. this._simulation._physicsUpdateList.add(this);
  26082. }
  26083. }
  26084. _parse(data) {
  26085. (data.friction != null) && (this.friction = data.friction);
  26086. (data.rollingFriction != null) && (this.rollingFriction = data.rollingFriction);
  26087. (data.restitution != null) && (this.restitution = data.restitution);
  26088. (data.isTrigger != null) && (this.isTrigger = data.isTrigger);
  26089. super._parse(data);
  26090. this._parseShape(data.shapes);
  26091. }
  26092. _onAdded() {
  26093. var physics3D = Physics3D._physics3D;
  26094. var btColObj = new physics3D.btCollisionObject();
  26095. btColObj.setUserIndex(this.id);
  26096. btColObj.forceActivationState(PhysicsComponent.ACTIVATIONSTATE_DISABLE_SIMULATION);
  26097. var flags = btColObj.getCollisionFlags();
  26098. if (this.owner.isStatic) {
  26099. if ((flags & PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT) > 0)
  26100. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  26101. flags = flags | PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT;
  26102. }
  26103. else {
  26104. if ((flags & PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT) > 0)
  26105. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT;
  26106. flags = flags | PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  26107. }
  26108. btColObj.setCollisionFlags(flags);
  26109. this._nativeColliderObject = btColObj;
  26110. super._onAdded();
  26111. }
  26112. }
  26113. class Rigidbody3D extends PhysicsTriggerComponent {
  26114. constructor(collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  26115. super(collisionGroup, canCollideWith);
  26116. this._isKinematic = false;
  26117. this._mass = 1.0;
  26118. this._gravity = new Vector3(0, -10, 0);
  26119. this._angularDamping = 0.0;
  26120. this._linearDamping = 0.0;
  26121. this._overrideGravity = false;
  26122. this._totalTorque = new Vector3(0, 0, 0);
  26123. this._totalForce = new Vector3(0, 0, 0);
  26124. this._linearVelocity = new Vector3();
  26125. this._angularVelocity = new Vector3();
  26126. this._linearFactor = new Vector3(1, 1, 1);
  26127. this._angularFactor = new Vector3(1, 1, 1);
  26128. this._detectCollisions = true;
  26129. }
  26130. static __init__() {
  26131. Rigidbody3D._nativeTempVector30 = new Physics3D._physics3D.btVector3(0, 0, 0);
  26132. Rigidbody3D._nativeTempVector31 = new Physics3D._physics3D.btVector3(0, 0, 0);
  26133. Rigidbody3D._nativeVector3Zero = new Physics3D._physics3D.btVector3(0, 0, 0);
  26134. Rigidbody3D._nativeInertia = new Physics3D._physics3D.btVector3(0, 0, 0);
  26135. Rigidbody3D._nativeImpulse = new Physics3D._physics3D.btVector3(0, 0, 0);
  26136. Rigidbody3D._nativeImpulseOffset = new Physics3D._physics3D.btVector3(0, 0, 0);
  26137. Rigidbody3D._nativeGravity = new Physics3D._physics3D.btVector3(0, 0, 0);
  26138. }
  26139. get mass() {
  26140. return this._mass;
  26141. }
  26142. set mass(value) {
  26143. value = Math.max(value, 1e-07);
  26144. this._mass = value;
  26145. (this._isKinematic) || (this._updateMass(value));
  26146. }
  26147. get isKinematic() {
  26148. return this._isKinematic;
  26149. }
  26150. set isKinematic(value) {
  26151. this._isKinematic = value;
  26152. var canInSimulation = !!(this._simulation && this._enabled && this._colliderShape);
  26153. canInSimulation && this._removeFromSimulation();
  26154. var natColObj = this._nativeColliderObject;
  26155. var flags = natColObj.getCollisionFlags();
  26156. if (value) {
  26157. flags = flags | PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  26158. natColObj.setCollisionFlags(flags);
  26159. this._nativeColliderObject.forceActivationState(PhysicsComponent.ACTIVATIONSTATE_DISABLE_DEACTIVATION);
  26160. this._enableProcessCollisions = false;
  26161. this._updateMass(0);
  26162. }
  26163. else {
  26164. if ((flags & PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT) > 0)
  26165. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  26166. natColObj.setCollisionFlags(flags);
  26167. this._nativeColliderObject.setActivationState(PhysicsComponent.ACTIVATIONSTATE_ACTIVE_TAG);
  26168. this._enableProcessCollisions = true;
  26169. this._updateMass(this._mass);
  26170. }
  26171. var nativeZero = Rigidbody3D._nativeVector3Zero;
  26172. natColObj.setInterpolationLinearVelocity(nativeZero);
  26173. natColObj.setLinearVelocity(nativeZero);
  26174. natColObj.setInterpolationAngularVelocity(nativeZero);
  26175. natColObj.setAngularVelocity(nativeZero);
  26176. canInSimulation && this._addToSimulation();
  26177. }
  26178. get linearDamping() {
  26179. return this._linearDamping;
  26180. }
  26181. set linearDamping(value) {
  26182. this._linearDamping = value;
  26183. if (this._nativeColliderObject)
  26184. this._nativeColliderObject.setDamping(value, this._angularDamping);
  26185. }
  26186. get angularDamping() {
  26187. return this._angularDamping;
  26188. }
  26189. set angularDamping(value) {
  26190. this._angularDamping = value;
  26191. if (this._nativeColliderObject)
  26192. this._nativeColliderObject.setDamping(this._linearDamping, value);
  26193. }
  26194. get overrideGravity() {
  26195. return this._overrideGravity;
  26196. }
  26197. set overrideGravity(value) {
  26198. this._overrideGravity = value;
  26199. if (this._nativeColliderObject) {
  26200. var flag = this._nativeColliderObject.getFlags();
  26201. if (value) {
  26202. if ((flag & Rigidbody3D._BT_DISABLE_WORLD_GRAVITY) === 0)
  26203. this._nativeColliderObject.setFlags(flag | Rigidbody3D._BT_DISABLE_WORLD_GRAVITY);
  26204. }
  26205. else {
  26206. if ((flag & Rigidbody3D._BT_DISABLE_WORLD_GRAVITY) > 0)
  26207. this._nativeColliderObject.setFlags(flag ^ Rigidbody3D._BT_DISABLE_WORLD_GRAVITY);
  26208. }
  26209. }
  26210. }
  26211. get gravity() {
  26212. return this._gravity;
  26213. }
  26214. set gravity(value) {
  26215. this._gravity = value;
  26216. Rigidbody3D._nativeGravity.setValue(-value.x, value.y, value.z);
  26217. this._nativeColliderObject.setGravity(Rigidbody3D._nativeGravity);
  26218. }
  26219. get totalForce() {
  26220. if (this._nativeColliderObject) {
  26221. var nativeTotalForce = this._nativeColliderObject.getTotalForce();
  26222. Utils3D._convertToLayaVec3(nativeTotalForce, this._totalForce, true);
  26223. return this._totalForce;
  26224. }
  26225. return null;
  26226. }
  26227. get linearFactor() {
  26228. if (this._nativeColliderObject)
  26229. return this._linearFactor;
  26230. return null;
  26231. }
  26232. set linearFactor(value) {
  26233. this._linearFactor = value;
  26234. if (this._nativeColliderObject) {
  26235. var nativeValue = Rigidbody3D._nativeTempVector30;
  26236. Utils3D._convertToBulletVec3(value, nativeValue, false);
  26237. this._nativeColliderObject.setLinearFactor(nativeValue);
  26238. }
  26239. }
  26240. get linearVelocity() {
  26241. if (this._nativeColliderObject)
  26242. Utils3D._convertToLayaVec3(this._nativeColliderObject.getLinearVelocity(), this._linearVelocity, true);
  26243. return this._linearVelocity;
  26244. }
  26245. set linearVelocity(value) {
  26246. this._linearVelocity = value;
  26247. if (this._nativeColliderObject) {
  26248. var nativeValue = Rigidbody3D._nativeTempVector30;
  26249. Utils3D._convertToBulletVec3(value, nativeValue, true);
  26250. (this.isSleeping) && (this.wakeUp());
  26251. this._nativeColliderObject.setLinearVelocity(nativeValue);
  26252. }
  26253. }
  26254. get angularFactor() {
  26255. if (this._nativeColliderObject)
  26256. return this._angularFactor;
  26257. return null;
  26258. }
  26259. set angularFactor(value) {
  26260. this._angularFactor = value;
  26261. if (this._nativeColliderObject) {
  26262. var nativeValue = Rigidbody3D._nativeTempVector30;
  26263. Utils3D._convertToBulletVec3(value, nativeValue, false);
  26264. this._nativeColliderObject.setAngularFactor(nativeValue);
  26265. }
  26266. }
  26267. get angularVelocity() {
  26268. if (this._nativeColliderObject)
  26269. Utils3D._convertToLayaVec3(this._nativeColliderObject.getAngularVelocity(), this._angularVelocity, true);
  26270. return this._angularVelocity;
  26271. }
  26272. set angularVelocity(value) {
  26273. this._angularVelocity = value;
  26274. if (this._nativeColliderObject) {
  26275. var nativeValue = Rigidbody3D._nativeTempVector30;
  26276. Utils3D._convertToBulletVec3(value, nativeValue, true);
  26277. (this.isSleeping) && (this.wakeUp());
  26278. this._nativeColliderObject.setAngularVelocity(nativeValue);
  26279. }
  26280. }
  26281. get totalTorque() {
  26282. if (this._nativeColliderObject) {
  26283. var nativeTotalTorque = this._nativeColliderObject.getTotalTorque();
  26284. Utils3D._convertToLayaVec3(nativeTotalTorque, this._totalTorque, true);
  26285. return this._totalTorque;
  26286. }
  26287. return null;
  26288. }
  26289. get detectCollisions() {
  26290. return this._detectCollisions;
  26291. }
  26292. set detectCollisions(value) {
  26293. if (this._detectCollisions !== value) {
  26294. this._detectCollisions = value;
  26295. if (this._colliderShape && this._enabled && this._simulation) {
  26296. this._simulation._removeRigidBody(this);
  26297. this._simulation._addRigidBody(this, this._collisionGroup, value ? this._canCollideWith : 0);
  26298. }
  26299. }
  26300. }
  26301. get isSleeping() {
  26302. if (this._nativeColliderObject)
  26303. return this._nativeColliderObject.getActivationState() === PhysicsComponent.ACTIVATIONSTATE_ISLAND_SLEEPING;
  26304. return false;
  26305. }
  26306. get sleepLinearVelocity() {
  26307. return this._nativeColliderObject.getLinearSleepingThreshold();
  26308. }
  26309. set sleepLinearVelocity(value) {
  26310. this._nativeColliderObject.setSleepingThresholds(value, this._nativeColliderObject.getAngularSleepingThreshold());
  26311. }
  26312. get sleepAngularVelocity() {
  26313. return this._nativeColliderObject.getAngularSleepingThreshold();
  26314. }
  26315. set sleepAngularVelocity(value) {
  26316. this._nativeColliderObject.setSleepingThresholds(this._nativeColliderObject.getLinearSleepingThreshold(), value);
  26317. }
  26318. _updateMass(mass) {
  26319. if (this._nativeColliderObject && this._colliderShape) {
  26320. this._colliderShape._nativeShape.calculateLocalInertia(mass, Rigidbody3D._nativeInertia);
  26321. this._nativeColliderObject.setMassProps(mass, Rigidbody3D._nativeInertia);
  26322. this._nativeColliderObject.updateInertiaTensor();
  26323. }
  26324. }
  26325. _delegateMotionStateGetWorldTransform(worldTransPointer) {
  26326. }
  26327. _delegateMotionStateSetWorldTransform(worldTransPointer) {
  26328. var rigidBody = this._rigidbody;
  26329. rigidBody._simulation._updatedRigidbodies++;
  26330. var physics3D = Physics3D._physics3D;
  26331. var worldTrans = physics3D.wrapPointer(worldTransPointer, physics3D.btTransform);
  26332. rigidBody._updateTransformComponent(worldTrans);
  26333. }
  26334. _delegateMotionStateGetWorldTransformNative(ridgidBody3D, worldTransPointer) {
  26335. }
  26336. _delegateMotionStateSetWorldTransformNative(rigidBody3D, worldTransPointer) {
  26337. var rigidBody = rigidBody3D;
  26338. rigidBody._simulation._updatedRigidbodies++;
  26339. var physics3D = Physics3D._physics3D;
  26340. var worldTrans = physics3D.wrapPointer(worldTransPointer, physics3D.btTransform);
  26341. rigidBody._updateTransformComponent(worldTrans);
  26342. }
  26343. _onScaleChange(scale) {
  26344. super._onScaleChange(scale);
  26345. this._updateMass(this._isKinematic ? 0 : this._mass);
  26346. }
  26347. _delegateMotionStateClear() {
  26348. this._rigidbody = null;
  26349. }
  26350. _onAdded() {
  26351. var physics3D = Physics3D._physics3D;
  26352. var motionState = new physics3D.LayaMotionState();
  26353. var isConchApp = (window.conch != null);
  26354. if (isConchApp && physics3D.LayaMotionState.prototype.setRigidbody) {
  26355. motionState.setRigidbody(this);
  26356. motionState.setNativeGetWorldTransform(this._delegateMotionStateGetWorldTransformNative);
  26357. motionState.setNativeSetWorldTransform(this._delegateMotionStateSetWorldTransformNative);
  26358. }
  26359. else {
  26360. motionState.getWorldTransform = this._delegateMotionStateGetWorldTransform;
  26361. motionState.setWorldTransform = this._delegateMotionStateSetWorldTransform;
  26362. }
  26363. motionState.clear = this._delegateMotionStateClear;
  26364. motionState._rigidbody = this;
  26365. this._nativeMotionState = motionState;
  26366. var constructInfo = new physics3D.btRigidBodyConstructionInfo(0.0, motionState, null, Rigidbody3D._nativeVector3Zero);
  26367. var btRigid = new physics3D.btRigidBody(constructInfo);
  26368. btRigid.setUserIndex(this.id);
  26369. this._nativeColliderObject = btRigid;
  26370. super._onAdded();
  26371. this.mass = this._mass;
  26372. this.linearFactor = this._linearFactor;
  26373. this.angularFactor = this._angularFactor;
  26374. this.linearDamping = this._linearDamping;
  26375. this.angularDamping = this._angularDamping;
  26376. this.overrideGravity = this._overrideGravity;
  26377. this.gravity = this._gravity;
  26378. this.isKinematic = this._isKinematic;
  26379. physics3D.destroy(constructInfo);
  26380. }
  26381. _onShapeChange(colShape) {
  26382. super._onShapeChange(colShape);
  26383. if (this._isKinematic) {
  26384. this._updateMass(0);
  26385. }
  26386. else {
  26387. this._nativeColliderObject.setCenterOfMassTransform(this._nativeColliderObject.getWorldTransform());
  26388. this._updateMass(this._mass);
  26389. }
  26390. }
  26391. _parse(data) {
  26392. (data.friction != null) && (this.friction = data.friction);
  26393. (data.rollingFriction != null) && (this.rollingFriction = data.rollingFriction);
  26394. (data.restitution != null) && (this.restitution = data.restitution);
  26395. (data.isTrigger != null) && (this.isTrigger = data.isTrigger);
  26396. (data.mass != null) && (this.mass = data.mass);
  26397. (data.isKinematic != null) && (this.isKinematic = data.isKinematic);
  26398. (data.linearDamping != null) && (this.linearDamping = data.linearDamping);
  26399. (data.angularDamping != null) && (this.angularDamping = data.angularDamping);
  26400. (data.overrideGravity != null) && (this.overrideGravity = data.overrideGravity);
  26401. if (data.gravity) {
  26402. this.gravity.fromArray(data.gravity);
  26403. this.gravity = this.gravity;
  26404. }
  26405. super._parse(data);
  26406. this._parseShape(data.shapes);
  26407. }
  26408. _onDestroy() {
  26409. var physics3D = Physics3D._physics3D;
  26410. this._nativeMotionState.clear();
  26411. physics3D.destroy(this._nativeMotionState);
  26412. super._onDestroy();
  26413. this._nativeMotionState = null;
  26414. this._gravity = null;
  26415. this._totalTorque = null;
  26416. this._linearVelocity = null;
  26417. this._angularVelocity = null;
  26418. this._linearFactor = null;
  26419. this._angularFactor = null;
  26420. }
  26421. _addToSimulation() {
  26422. this._simulation._addRigidBody(this, this._collisionGroup, this._detectCollisions ? this._canCollideWith : 0);
  26423. }
  26424. _removeFromSimulation() {
  26425. this._simulation._removeRigidBody(this);
  26426. }
  26427. _cloneTo(dest) {
  26428. super._cloneTo(dest);
  26429. var destRigidbody3D = dest;
  26430. destRigidbody3D.isKinematic = this._isKinematic;
  26431. destRigidbody3D.mass = this._mass;
  26432. destRigidbody3D.gravity = this._gravity;
  26433. destRigidbody3D.angularDamping = this._angularDamping;
  26434. destRigidbody3D.linearDamping = this._linearDamping;
  26435. destRigidbody3D.overrideGravity = this._overrideGravity;
  26436. destRigidbody3D.linearVelocity = this._linearVelocity;
  26437. destRigidbody3D.angularVelocity = this._angularVelocity;
  26438. destRigidbody3D.linearFactor = this._linearFactor;
  26439. destRigidbody3D.angularFactor = this._angularFactor;
  26440. destRigidbody3D.detectCollisions = this._detectCollisions;
  26441. }
  26442. applyForce(force, localOffset = null) {
  26443. if (this._nativeColliderObject == null)
  26444. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  26445. var nativeForce = Rigidbody3D._nativeTempVector30;
  26446. nativeForce.setValue(-force.x, force.y, force.z);
  26447. if (localOffset) {
  26448. var nativeOffset = Rigidbody3D._nativeTempVector31;
  26449. nativeOffset.setValue(-localOffset.x, localOffset.y, localOffset.z);
  26450. this._nativeColliderObject.applyForce(nativeForce, nativeOffset);
  26451. }
  26452. else {
  26453. this._nativeColliderObject.applyCentralForce(nativeForce);
  26454. }
  26455. }
  26456. applyTorque(torque) {
  26457. if (this._nativeColliderObject == null)
  26458. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  26459. var nativeTorque = Rigidbody3D._nativeTempVector30;
  26460. nativeTorque.setValue(-torque.x, torque.y, torque.z);
  26461. this._nativeColliderObject.applyTorque(nativeTorque);
  26462. }
  26463. applyImpulse(impulse, localOffset = null) {
  26464. if (this._nativeColliderObject == null)
  26465. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  26466. Rigidbody3D._nativeImpulse.setValue(-impulse.x, impulse.y, impulse.z);
  26467. if (localOffset) {
  26468. Rigidbody3D._nativeImpulseOffset.setValue(-localOffset.x, localOffset.y, localOffset.z);
  26469. this._nativeColliderObject.applyImpulse(Rigidbody3D._nativeImpulse, Rigidbody3D._nativeImpulseOffset);
  26470. }
  26471. else {
  26472. this._nativeColliderObject.applyCentralImpulse(Rigidbody3D._nativeImpulse);
  26473. }
  26474. }
  26475. applyTorqueImpulse(torqueImpulse) {
  26476. if (this._nativeColliderObject == null)
  26477. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  26478. var nativeTorqueImpulse = Rigidbody3D._nativeTempVector30;
  26479. nativeTorqueImpulse.setValue(-torqueImpulse.x, torqueImpulse.y, torqueImpulse.z);
  26480. this._nativeColliderObject.applyTorqueImpulse(nativeTorqueImpulse);
  26481. }
  26482. wakeUp() {
  26483. this._nativeColliderObject && (this._nativeColliderObject.activate(false));
  26484. }
  26485. clearForces() {
  26486. var rigidBody = this._nativeColliderObject;
  26487. if (rigidBody == null)
  26488. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  26489. rigidBody.clearForces();
  26490. var nativeZero = Rigidbody3D._nativeVector3Zero;
  26491. rigidBody.setInterpolationLinearVelocity(nativeZero);
  26492. rigidBody.setLinearVelocity(nativeZero);
  26493. rigidBody.setInterpolationAngularVelocity(nativeZero);
  26494. rigidBody.setAngularVelocity(nativeZero);
  26495. }
  26496. }
  26497. Rigidbody3D.TYPE_STATIC = 0;
  26498. Rigidbody3D.TYPE_DYNAMIC = 1;
  26499. Rigidbody3D.TYPE_KINEMATIC = 2;
  26500. Rigidbody3D._BT_DISABLE_WORLD_GRAVITY = 1;
  26501. Rigidbody3D._BT_ENABLE_GYROPSCOPIC_FORCE = 2;
  26502. class StaticPlaneColliderShape extends ColliderShape {
  26503. static __init__() {
  26504. StaticPlaneColliderShape._nativeNormal = new Physics3D._physics3D.btVector3(0, 0, 0);
  26505. }
  26506. constructor(normal, offset) {
  26507. super();
  26508. this._normal = normal;
  26509. this._offset = offset;
  26510. this._type = ColliderShape.SHAPETYPES_STATICPLANE;
  26511. StaticPlaneColliderShape._nativeNormal.setValue(-normal.x, normal.y, normal.z);
  26512. this._nativeShape = new Physics3D._physics3D.btStaticPlaneShape(StaticPlaneColliderShape._nativeNormal, offset);
  26513. }
  26514. clone() {
  26515. var dest = new StaticPlaneColliderShape(this._normal, this._offset);
  26516. this.cloneTo(dest);
  26517. return dest;
  26518. }
  26519. }
  26520. class SubMesh extends GeometryElement {
  26521. constructor(mesh) {
  26522. super();
  26523. this._id = ++SubMesh._uniqueIDCounter;
  26524. this._mesh = mesh;
  26525. this._boneIndicesList = [];
  26526. this._subIndexBufferStart = [];
  26527. this._subIndexBufferCount = [];
  26528. }
  26529. get indexCount() {
  26530. return this._indexCount;
  26531. }
  26532. _setIndexRange(indexStart, indexCount) {
  26533. this._indexStart = indexStart;
  26534. this._indexCount = indexCount;
  26535. this._indices = new Uint16Array(this._indexBuffer.getData().buffer, indexStart * 2, indexCount);
  26536. }
  26537. _getType() {
  26538. return SubMesh._type;
  26539. }
  26540. _prepareRender(state) {
  26541. this._mesh._uploadVerticesData();
  26542. return true;
  26543. }
  26544. _render(state) {
  26545. var gl = Laya.LayaGL.instance;
  26546. this._mesh._bufferState.bind();
  26547. var skinnedDatas = state.renderElement.render._skinnedData;
  26548. if (skinnedDatas) {
  26549. var subSkinnedDatas = skinnedDatas[this._indexInMesh];
  26550. var boneIndicesListCount = this._boneIndicesList.length;
  26551. for (var i = 0; i < boneIndicesListCount; i++) {
  26552. state.shader.uploadCustomUniform(SkinnedMeshSprite3D.BONES, subSkinnedDatas[i]);
  26553. gl.drawElements(gl.TRIANGLES, this._subIndexBufferCount[i], gl.UNSIGNED_SHORT, this._subIndexBufferStart[i] * 2);
  26554. }
  26555. }
  26556. else {
  26557. gl.drawElements(gl.TRIANGLES, this._indexCount, gl.UNSIGNED_SHORT, this._indexStart * 2);
  26558. }
  26559. Laya.Stat.trianglesFaces += this._indexCount / 3;
  26560. Laya.Stat.renderBatches++;
  26561. }
  26562. getIndices() {
  26563. if (this._mesh._isReadable)
  26564. return this._indices.slice();
  26565. else
  26566. throw "SubMesh:can't get indices on subMesh,mesh's isReadable must be true.";
  26567. }
  26568. setIndices(indices) {
  26569. this._indexBuffer.setData(indices, this._indexStart, 0, this._indexCount);
  26570. }
  26571. destroy() {
  26572. if (this._destroyed)
  26573. return;
  26574. super.destroy();
  26575. this._indexBuffer.destroy();
  26576. this._indexBuffer = null;
  26577. this._mesh = null;
  26578. this._boneIndicesList = null;
  26579. this._subIndexBufferStart = null;
  26580. this._subIndexBufferCount = null;
  26581. this._skinAnimationDatas = null;
  26582. }
  26583. }
  26584. SubMesh._uniqueIDCounter = 0;
  26585. SubMesh._type = GeometryElement._typeCounter++;
  26586. class LoadModelV04 {
  26587. static parse(readData, version, mesh, subMeshes) {
  26588. LoadModelV04._mesh = mesh;
  26589. LoadModelV04._subMeshes = subMeshes;
  26590. LoadModelV04._version = version;
  26591. LoadModelV04._readData = readData;
  26592. LoadModelV04.READ_DATA();
  26593. LoadModelV04.READ_BLOCK();
  26594. LoadModelV04.READ_STRINGS();
  26595. for (var i = 0, n = LoadModelV04._BLOCK.count; i < n; i++) {
  26596. LoadModelV04._readData.pos = LoadModelV04._BLOCK.blockStarts[i];
  26597. var index = LoadModelV04._readData.getUint16();
  26598. var blockName = LoadModelV04._strings[index];
  26599. var fn = LoadModelV04["READ_" + blockName];
  26600. if (fn == null)
  26601. throw new Error("model file err,no this function:" + index + " " + blockName);
  26602. else
  26603. fn.call(null);
  26604. }
  26605. LoadModelV04._mesh._bindPoseIndices = new Uint16Array(LoadModelV04._bindPoseIndices);
  26606. LoadModelV04._bindPoseIndices.length = 0;
  26607. LoadModelV04._strings.length = 0;
  26608. LoadModelV04._readData = null;
  26609. LoadModelV04._version = null;
  26610. LoadModelV04._mesh = null;
  26611. LoadModelV04._subMeshes = null;
  26612. }
  26613. static _readString() {
  26614. return LoadModelV04._strings[LoadModelV04._readData.getUint16()];
  26615. }
  26616. static READ_DATA() {
  26617. LoadModelV04._DATA.offset = LoadModelV04._readData.getUint32();
  26618. LoadModelV04._DATA.size = LoadModelV04._readData.getUint32();
  26619. }
  26620. static READ_BLOCK() {
  26621. var count = LoadModelV04._BLOCK.count = LoadModelV04._readData.getUint16();
  26622. var blockStarts = LoadModelV04._BLOCK.blockStarts = [];
  26623. var blockLengths = LoadModelV04._BLOCK.blockLengths = [];
  26624. for (var i = 0; i < count; i++) {
  26625. blockStarts.push(LoadModelV04._readData.getUint32());
  26626. blockLengths.push(LoadModelV04._readData.getUint32());
  26627. }
  26628. }
  26629. static READ_STRINGS() {
  26630. var offset = LoadModelV04._readData.getUint32();
  26631. var count = LoadModelV04._readData.getUint16();
  26632. var prePos = LoadModelV04._readData.pos;
  26633. LoadModelV04._readData.pos = offset + LoadModelV04._DATA.offset;
  26634. for (var i = 0; i < count; i++)
  26635. LoadModelV04._strings[i] = LoadModelV04._readData.readUTFString();
  26636. LoadModelV04._readData.pos = prePos;
  26637. }
  26638. static READ_MESH() {
  26639. var gl = Laya.LayaGL.instance;
  26640. var name = LoadModelV04._readString();
  26641. var arrayBuffer = LoadModelV04._readData.__getBuffer();
  26642. var i;
  26643. var memorySize = 0;
  26644. var vertexBufferCount = LoadModelV04._readData.getInt16();
  26645. var offset = LoadModelV04._DATA.offset;
  26646. for (i = 0; i < vertexBufferCount; i++) {
  26647. var vbStart = offset + LoadModelV04._readData.getUint32();
  26648. var vbLength = LoadModelV04._readData.getUint32();
  26649. var vbArrayBuffer = arrayBuffer.slice(vbStart, vbStart + vbLength);
  26650. var vbDatas = new Float32Array(vbArrayBuffer);
  26651. var bufferAttribute = LoadModelV04._readString();
  26652. var vertexDeclaration;
  26653. switch (LoadModelV04._version) {
  26654. case "LAYAMODEL:0301":
  26655. case "LAYAMODEL:0400":
  26656. vertexDeclaration = VertexMesh.getVertexDeclaration(bufferAttribute);
  26657. break;
  26658. case "LAYAMODEL:0401":
  26659. vertexDeclaration = VertexMesh.getVertexDeclaration(bufferAttribute, false);
  26660. break;
  26661. default:
  26662. throw new Error("LoadModelV03: unknown version.");
  26663. }
  26664. if (!vertexDeclaration)
  26665. throw new Error("LoadModelV03: unknown vertexDeclaration.");
  26666. var vertexBuffer = new VertexBuffer3D(vbDatas.length * 4, gl.STATIC_DRAW, true);
  26667. vertexBuffer.vertexDeclaration = vertexDeclaration;
  26668. vertexBuffer.setData(vbDatas.buffer);
  26669. LoadModelV04._mesh._vertexBuffer = vertexBuffer;
  26670. LoadModelV04._mesh._vertexCount += vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  26671. memorySize += vbDatas.length * 4;
  26672. }
  26673. var ibStart = offset + LoadModelV04._readData.getUint32();
  26674. var ibLength = LoadModelV04._readData.getUint32();
  26675. var ibDatas = new Uint16Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  26676. var indexBuffer = new IndexBuffer3D(IndexBuffer3D.INDEXTYPE_USHORT, ibLength / 2, gl.STATIC_DRAW, true);
  26677. indexBuffer.setData(ibDatas);
  26678. LoadModelV04._mesh._indexBuffer = indexBuffer;
  26679. memorySize += indexBuffer.indexCount * 2;
  26680. LoadModelV04._mesh._setBuffer(LoadModelV04._mesh._vertexBuffer, indexBuffer);
  26681. LoadModelV04._mesh._setCPUMemory(memorySize);
  26682. LoadModelV04._mesh._setGPUMemory(memorySize);
  26683. var boneNames = LoadModelV04._mesh._boneNames = [];
  26684. var boneCount = LoadModelV04._readData.getUint16();
  26685. boneNames.length = boneCount;
  26686. for (i = 0; i < boneCount; i++)
  26687. boneNames[i] = LoadModelV04._strings[LoadModelV04._readData.getUint16()];
  26688. LoadModelV04._readData.pos += 8;
  26689. var bindPoseDataStart = LoadModelV04._readData.getUint32();
  26690. var bindPoseDataLength = LoadModelV04._readData.getUint32();
  26691. var bindPoseDatas = new Float32Array(arrayBuffer.slice(offset + bindPoseDataStart, offset + bindPoseDataStart + bindPoseDataLength));
  26692. var bindPoseFloatCount = bindPoseDatas.length;
  26693. var bindPoseBuffer = LoadModelV04._mesh._inverseBindPosesBuffer = new ArrayBuffer(bindPoseFloatCount * 4);
  26694. LoadModelV04._mesh._inverseBindPoses = [];
  26695. for (i = 0; i < bindPoseFloatCount; i += 16) {
  26696. 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));
  26697. LoadModelV04._mesh._inverseBindPoses[i / 16] = inverseGlobalBindPose;
  26698. }
  26699. return true;
  26700. }
  26701. static READ_SUBMESH() {
  26702. var arrayBuffer = LoadModelV04._readData.__getBuffer();
  26703. var subMesh = new SubMesh(LoadModelV04._mesh);
  26704. LoadModelV04._readData.getInt16();
  26705. LoadModelV04._readData.getUint32();
  26706. LoadModelV04._readData.getUint32();
  26707. var ibStart = LoadModelV04._readData.getUint32();
  26708. var ibCount = LoadModelV04._readData.getUint32();
  26709. var indexBuffer = LoadModelV04._mesh._indexBuffer;
  26710. subMesh._indexBuffer = indexBuffer;
  26711. subMesh._setIndexRange(ibStart, ibCount);
  26712. var vertexBuffer = LoadModelV04._mesh._vertexBuffer;
  26713. subMesh._vertexBuffer = vertexBuffer;
  26714. var offset = LoadModelV04._DATA.offset;
  26715. var subIndexBufferStart = subMesh._subIndexBufferStart;
  26716. var subIndexBufferCount = subMesh._subIndexBufferCount;
  26717. var boneIndicesList = subMesh._boneIndicesList;
  26718. var drawCount = LoadModelV04._readData.getUint16();
  26719. subIndexBufferStart.length = drawCount;
  26720. subIndexBufferCount.length = drawCount;
  26721. boneIndicesList.length = drawCount;
  26722. var pathMarks = LoadModelV04._mesh._skinDataPathMarks;
  26723. var bindPoseIndices = LoadModelV04._bindPoseIndices;
  26724. var subMeshIndex = LoadModelV04._subMeshes.length;
  26725. for (var i = 0; i < drawCount; i++) {
  26726. subIndexBufferStart[i] = LoadModelV04._readData.getUint32();
  26727. subIndexBufferCount[i] = LoadModelV04._readData.getUint32();
  26728. var boneDicofs = LoadModelV04._readData.getUint32();
  26729. var boneDicCount = LoadModelV04._readData.getUint32();
  26730. var boneIndices = boneIndicesList[i] = new Uint16Array(arrayBuffer.slice(offset + boneDicofs, offset + boneDicofs + boneDicCount));
  26731. for (var j = 0, m = boneIndices.length; j < m; j++) {
  26732. var index = boneIndices[j];
  26733. var combineIndex = bindPoseIndices.indexOf(index);
  26734. if (combineIndex === -1) {
  26735. boneIndices[j] = bindPoseIndices.length;
  26736. bindPoseIndices.push(index);
  26737. pathMarks.push([subMeshIndex, i, j]);
  26738. }
  26739. else {
  26740. boneIndices[j] = combineIndex;
  26741. }
  26742. }
  26743. }
  26744. LoadModelV04._subMeshes.push(subMesh);
  26745. return true;
  26746. }
  26747. }
  26748. LoadModelV04._BLOCK = { count: 0 };
  26749. LoadModelV04._DATA = { offset: 0, size: 0 };
  26750. LoadModelV04._strings = [];
  26751. LoadModelV04._bindPoseIndices = [];
  26752. class LoadModelV05 {
  26753. static parse(readData, version, mesh, subMeshes) {
  26754. LoadModelV05._mesh = mesh;
  26755. LoadModelV05._subMeshes = subMeshes;
  26756. LoadModelV05._version = version;
  26757. LoadModelV05._readData = readData;
  26758. LoadModelV05.READ_DATA();
  26759. LoadModelV05.READ_BLOCK();
  26760. LoadModelV05.READ_STRINGS();
  26761. for (var i = 0, n = LoadModelV05._BLOCK.count; i < n; i++) {
  26762. LoadModelV05._readData.pos = LoadModelV05._BLOCK.blockStarts[i];
  26763. var index = LoadModelV05._readData.getUint16();
  26764. var blockName = LoadModelV05._strings[index];
  26765. var fn = LoadModelV05["READ_" + blockName];
  26766. if (fn == null)
  26767. throw new Error("model file err,no this function:" + index + " " + blockName);
  26768. else
  26769. fn.call(null);
  26770. }
  26771. LoadModelV05._mesh._bindPoseIndices = new Uint16Array(LoadModelV05._bindPoseIndices);
  26772. LoadModelV05._bindPoseIndices.length = 0;
  26773. LoadModelV05._strings.length = 0;
  26774. LoadModelV05._readData = null;
  26775. LoadModelV05._version = null;
  26776. LoadModelV05._mesh = null;
  26777. LoadModelV05._subMeshes = null;
  26778. }
  26779. static _readString() {
  26780. return LoadModelV05._strings[LoadModelV05._readData.getUint16()];
  26781. }
  26782. static READ_DATA() {
  26783. LoadModelV05._DATA.offset = LoadModelV05._readData.getUint32();
  26784. LoadModelV05._DATA.size = LoadModelV05._readData.getUint32();
  26785. }
  26786. static READ_BLOCK() {
  26787. var count = LoadModelV05._BLOCK.count = LoadModelV05._readData.getUint16();
  26788. var blockStarts = LoadModelV05._BLOCK.blockStarts = [];
  26789. var blockLengths = LoadModelV05._BLOCK.blockLengths = [];
  26790. for (var i = 0; i < count; i++) {
  26791. blockStarts.push(LoadModelV05._readData.getUint32());
  26792. blockLengths.push(LoadModelV05._readData.getUint32());
  26793. }
  26794. }
  26795. static READ_STRINGS() {
  26796. var offset = LoadModelV05._readData.getUint32();
  26797. var count = LoadModelV05._readData.getUint16();
  26798. var prePos = LoadModelV05._readData.pos;
  26799. LoadModelV05._readData.pos = offset + LoadModelV05._DATA.offset;
  26800. for (var i = 0; i < count; i++)
  26801. LoadModelV05._strings[i] = LoadModelV05._readData.readUTFString();
  26802. LoadModelV05._readData.pos = prePos;
  26803. }
  26804. static READ_MESH() {
  26805. var gl = Laya.LayaGL.instance;
  26806. var i;
  26807. var memorySize = 0;
  26808. var name = LoadModelV05._readString();
  26809. var arrayBuffer = LoadModelV05._readData.__getBuffer();
  26810. var vertexBufferCount = LoadModelV05._readData.getInt16();
  26811. var offset = LoadModelV05._DATA.offset;
  26812. for (i = 0; i < vertexBufferCount; i++) {
  26813. var vbStart = offset + LoadModelV05._readData.getUint32();
  26814. var vertexCount = LoadModelV05._readData.getUint32();
  26815. var vertexFlag = LoadModelV05._readString();
  26816. var vertexDeclaration = VertexMesh.getVertexDeclaration(vertexFlag, false);
  26817. var vertexStride = vertexDeclaration.vertexStride;
  26818. var vertexData;
  26819. var floatData;
  26820. var uint8Data;
  26821. var subVertexFlags = vertexFlag.split(",");
  26822. var subVertexCount = subVertexFlags.length;
  26823. switch (LoadModelV05._version) {
  26824. case "LAYAMODEL:05":
  26825. vertexData = arrayBuffer.slice(vbStart, vbStart + vertexCount * vertexStride);
  26826. floatData = new Float32Array(vertexData);
  26827. uint8Data = new Uint8Array(vertexData);
  26828. break;
  26829. case "LAYAMODEL:COMPRESSION_05":
  26830. vertexData = new ArrayBuffer(vertexStride * vertexCount);
  26831. floatData = new Float32Array(vertexData);
  26832. uint8Data = new Uint8Array(vertexData);
  26833. var lastPosition = LoadModelV05._readData.pos;
  26834. LoadModelV05._readData.pos = vbStart;
  26835. for (var j = 0; j < vertexCount; j++) {
  26836. var subOffset;
  26837. var verOffset = j * vertexStride;
  26838. for (var k = 0; k < subVertexCount; k++) {
  26839. switch (subVertexFlags[k]) {
  26840. case "POSITION":
  26841. subOffset = verOffset / 4;
  26842. floatData[subOffset] = HalfFloatUtils.convertToNumber(LoadModelV05._readData.getUint16());
  26843. floatData[subOffset + 1] = HalfFloatUtils.convertToNumber(LoadModelV05._readData.getUint16());
  26844. floatData[subOffset + 2] = HalfFloatUtils.convertToNumber(LoadModelV05._readData.getUint16());
  26845. verOffset += 12;
  26846. break;
  26847. case "NORMAL":
  26848. subOffset = verOffset / 4;
  26849. floatData[subOffset] = LoadModelV05._readData.getUint8() / 127.5 - 1;
  26850. floatData[subOffset + 1] = LoadModelV05._readData.getUint8() / 127.5 - 1;
  26851. floatData[subOffset + 2] = LoadModelV05._readData.getUint8() / 127.5 - 1;
  26852. verOffset += 12;
  26853. break;
  26854. case "COLOR":
  26855. subOffset = verOffset / 4;
  26856. floatData[subOffset] = LoadModelV05._readData.getUint8() / 255;
  26857. floatData[subOffset + 1] = LoadModelV05._readData.getUint8() / 255;
  26858. floatData[subOffset + 2] = LoadModelV05._readData.getUint8() / 255;
  26859. floatData[subOffset + 3] = LoadModelV05._readData.getUint8() / 255;
  26860. verOffset += 16;
  26861. break;
  26862. case "UV":
  26863. subOffset = verOffset / 4;
  26864. floatData[subOffset] = HalfFloatUtils.convertToNumber(LoadModelV05._readData.getUint16());
  26865. floatData[subOffset + 1] = HalfFloatUtils.convertToNumber(LoadModelV05._readData.getUint16());
  26866. verOffset += 8;
  26867. break;
  26868. case "UV1":
  26869. subOffset = verOffset / 4;
  26870. floatData[subOffset] = HalfFloatUtils.convertToNumber(LoadModelV05._readData.getUint16());
  26871. floatData[subOffset + 1] = HalfFloatUtils.convertToNumber(LoadModelV05._readData.getUint16());
  26872. verOffset += 8;
  26873. break;
  26874. case "BLENDWEIGHT":
  26875. subOffset = verOffset / 4;
  26876. floatData[subOffset] = LoadModelV05._readData.getUint8() / 255;
  26877. floatData[subOffset + 1] = LoadModelV05._readData.getUint8() / 255;
  26878. floatData[subOffset + 2] = LoadModelV05._readData.getUint8() / 255;
  26879. floatData[subOffset + 3] = LoadModelV05._readData.getUint8() / 255;
  26880. verOffset += 16;
  26881. break;
  26882. case "BLENDINDICES":
  26883. uint8Data[verOffset] = LoadModelV05._readData.getUint8();
  26884. uint8Data[verOffset + 1] = LoadModelV05._readData.getUint8();
  26885. uint8Data[verOffset + 2] = LoadModelV05._readData.getUint8();
  26886. uint8Data[verOffset + 3] = LoadModelV05._readData.getUint8();
  26887. verOffset += 4;
  26888. break;
  26889. case "TANGENT":
  26890. subOffset = verOffset / 4;
  26891. floatData[subOffset] = LoadModelV05._readData.getUint8() / 127.5 - 1;
  26892. floatData[subOffset + 1] = LoadModelV05._readData.getUint8() / 127.5 - 1;
  26893. floatData[subOffset + 2] = LoadModelV05._readData.getUint8() / 127.5 - 1;
  26894. floatData[subOffset + 3] = LoadModelV05._readData.getUint8() / 127.5 - 1;
  26895. verOffset += 16;
  26896. break;
  26897. }
  26898. }
  26899. }
  26900. LoadModelV05._readData.pos = lastPosition;
  26901. break;
  26902. }
  26903. var vertexBuffer = new VertexBuffer3D(vertexData.byteLength, gl.STATIC_DRAW, true);
  26904. vertexBuffer.vertexDeclaration = vertexDeclaration;
  26905. vertexBuffer.setData(vertexData);
  26906. LoadModelV05._mesh._vertexBuffer = vertexBuffer;
  26907. LoadModelV05._mesh._vertexCount += vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  26908. memorySize += floatData.length * 4;
  26909. }
  26910. var ibStart = offset + LoadModelV05._readData.getUint32();
  26911. var ibLength = LoadModelV05._readData.getUint32();
  26912. var ibDatas = new Uint16Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  26913. var indexBuffer = new IndexBuffer3D(IndexBuffer3D.INDEXTYPE_USHORT, ibLength / 2, gl.STATIC_DRAW, true);
  26914. indexBuffer.setData(ibDatas);
  26915. LoadModelV05._mesh._indexBuffer = indexBuffer;
  26916. LoadModelV05._mesh._setBuffer(LoadModelV05._mesh._vertexBuffer, indexBuffer);
  26917. memorySize += indexBuffer.indexCount * 2;
  26918. LoadModelV05._mesh._setCPUMemory(memorySize);
  26919. LoadModelV05._mesh._setGPUMemory(memorySize);
  26920. var boneNames = LoadModelV05._mesh._boneNames = [];
  26921. var boneCount = LoadModelV05._readData.getUint16();
  26922. boneNames.length = boneCount;
  26923. for (i = 0; i < boneCount; i++)
  26924. boneNames[i] = LoadModelV05._strings[LoadModelV05._readData.getUint16()];
  26925. var bindPoseDataStart = LoadModelV05._readData.getUint32();
  26926. var bindPoseDataLength = LoadModelV05._readData.getUint32();
  26927. var bindPoseDatas = new Float32Array(arrayBuffer.slice(offset + bindPoseDataStart, offset + bindPoseDataStart + bindPoseDataLength));
  26928. var bindPoseFloatCount = bindPoseDatas.length;
  26929. var bindPoseBuffer = LoadModelV05._mesh._inverseBindPosesBuffer = new ArrayBuffer(bindPoseFloatCount * 4);
  26930. LoadModelV05._mesh._inverseBindPoses = [];
  26931. for (i = 0; i < bindPoseFloatCount; i += 16) {
  26932. 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));
  26933. LoadModelV05._mesh._inverseBindPoses[i / 16] = inverseGlobalBindPose;
  26934. }
  26935. return true;
  26936. }
  26937. static READ_SUBMESH() {
  26938. var arrayBuffer = LoadModelV05._readData.__getBuffer();
  26939. var subMesh = new SubMesh(LoadModelV05._mesh);
  26940. LoadModelV05._readData.getInt16();
  26941. var ibStart = LoadModelV05._readData.getUint32();
  26942. var ibCount = LoadModelV05._readData.getUint32();
  26943. var indexBuffer = LoadModelV05._mesh._indexBuffer;
  26944. subMesh._indexBuffer = indexBuffer;
  26945. subMesh._setIndexRange(ibStart, ibCount);
  26946. var vertexBuffer = LoadModelV05._mesh._vertexBuffer;
  26947. subMesh._vertexBuffer = vertexBuffer;
  26948. var offset = LoadModelV05._DATA.offset;
  26949. var subIndexBufferStart = subMesh._subIndexBufferStart;
  26950. var subIndexBufferCount = subMesh._subIndexBufferCount;
  26951. var boneIndicesList = subMesh._boneIndicesList;
  26952. var drawCount = LoadModelV05._readData.getUint16();
  26953. subIndexBufferStart.length = drawCount;
  26954. subIndexBufferCount.length = drawCount;
  26955. boneIndicesList.length = drawCount;
  26956. var pathMarks = LoadModelV05._mesh._skinDataPathMarks;
  26957. var bindPoseIndices = LoadModelV05._bindPoseIndices;
  26958. var subMeshIndex = LoadModelV05._subMeshes.length;
  26959. for (var i = 0; i < drawCount; i++) {
  26960. subIndexBufferStart[i] = LoadModelV05._readData.getUint32();
  26961. subIndexBufferCount[i] = LoadModelV05._readData.getUint32();
  26962. var boneDicofs = LoadModelV05._readData.getUint32();
  26963. var boneDicCount = LoadModelV05._readData.getUint32();
  26964. var boneIndices = boneIndicesList[i] = new Uint16Array(arrayBuffer.slice(offset + boneDicofs, offset + boneDicofs + boneDicCount));
  26965. for (var j = 0, m = boneIndices.length; j < m; j++) {
  26966. var index = boneIndices[j];
  26967. var combineIndex = bindPoseIndices.indexOf(index);
  26968. if (combineIndex === -1) {
  26969. boneIndices[j] = bindPoseIndices.length;
  26970. bindPoseIndices.push(index);
  26971. pathMarks.push([subMeshIndex, i, j]);
  26972. }
  26973. else {
  26974. boneIndices[j] = combineIndex;
  26975. }
  26976. }
  26977. }
  26978. LoadModelV05._subMeshes.push(subMesh);
  26979. return true;
  26980. }
  26981. }
  26982. LoadModelV05._BLOCK = { count: 0 };
  26983. LoadModelV05._DATA = { offset: 0, size: 0 };
  26984. LoadModelV05._strings = [];
  26985. LoadModelV05._bindPoseIndices = [];
  26986. class MeshReader {
  26987. constructor() {
  26988. }
  26989. static read(data, mesh, subMeshes) {
  26990. var readData = new Laya.Byte(data);
  26991. readData.pos = 0;
  26992. var version = readData.readUTFString();
  26993. switch (version) {
  26994. case "LAYAMODEL:0301":
  26995. case "LAYAMODEL:0400":
  26996. case "LAYAMODEL:0401":
  26997. LoadModelV04.parse(readData, version, mesh, subMeshes);
  26998. break;
  26999. case "LAYAMODEL:05":
  27000. case "LAYAMODEL:COMPRESSION_05":
  27001. LoadModelV05.parse(readData, version, mesh, subMeshes);
  27002. break;
  27003. default:
  27004. throw new Error("MeshReader: unknown mesh version.");
  27005. }
  27006. mesh._setSubMeshes(subMeshes);
  27007. }
  27008. }
  27009. class Mesh extends Laya.Resource {
  27010. constructor(isReadable = true) {
  27011. super();
  27012. this._tempVector30 = new Vector3();
  27013. this._tempVector31 = new Vector3();
  27014. this._tempVector32 = new Vector3();
  27015. this._minVerticesUpdate = -1;
  27016. this._maxVerticesUpdate = -1;
  27017. this._needUpdateBounds = true;
  27018. this._bounds = new Bounds(new Vector3(), new Vector3());
  27019. this._bufferState = new BufferState();
  27020. this._instanceBufferState = new BufferState();
  27021. this._vertexBuffer = null;
  27022. this._indexBuffer = null;
  27023. this._vertexCount = 0;
  27024. this._isReadable = isReadable;
  27025. this._subMeshes = [];
  27026. this._skinDataPathMarks = [];
  27027. }
  27028. static __init__() {
  27029. var physics3D = Physics3D._physics3D;
  27030. if (physics3D) {
  27031. Mesh._nativeTempVector30 = new physics3D.btVector3(0, 0, 0);
  27032. Mesh._nativeTempVector31 = new physics3D.btVector3(0, 0, 0);
  27033. Mesh._nativeTempVector32 = new physics3D.btVector3(0, 0, 0);
  27034. }
  27035. }
  27036. static _parse(data, propertyParams = null, constructParams = null) {
  27037. var mesh = new Mesh();
  27038. MeshReader.read(data, mesh, mesh._subMeshes);
  27039. return mesh;
  27040. }
  27041. static load(url, complete) {
  27042. Laya.ILaya.loader.create(url, complete, null, Mesh.MESH);
  27043. }
  27044. get inverseAbsoluteBindPoses() {
  27045. return this._inverseBindPoses;
  27046. }
  27047. get vertexCount() {
  27048. return this._vertexCount;
  27049. }
  27050. get indexCount() {
  27051. return this._indexBuffer.indexCount;
  27052. }
  27053. get subMeshCount() {
  27054. return this._subMeshes.length;
  27055. }
  27056. get bounds() {
  27057. return this._bounds;
  27058. }
  27059. set bounds(value) {
  27060. if (this._bounds !== value)
  27061. value.cloneTo(this._bounds);
  27062. }
  27063. _getPositionElement(vertexBuffer) {
  27064. var vertexElements = vertexBuffer.vertexDeclaration._vertexElements;
  27065. for (var i = 0, n = vertexElements.length; i < n; i++) {
  27066. var vertexElement = vertexElements[i];
  27067. if (vertexElement._elementFormat === VertexElementFormat.Vector3 && vertexElement._elementUsage === VertexMesh.MESH_POSITION0)
  27068. return vertexElement;
  27069. }
  27070. return null;
  27071. }
  27072. _getVerticeElementData(data, elementUsage) {
  27073. data.length = this._vertexCount;
  27074. var verDec = this._vertexBuffer.vertexDeclaration;
  27075. var element = verDec.getVertexElementByUsage(elementUsage);
  27076. if (element) {
  27077. var uint8Vertices = this._vertexBuffer.getUint8Data();
  27078. var floatVertices = this._vertexBuffer.getFloat32Data();
  27079. var uint8VerStr = verDec.vertexStride;
  27080. var floatVerStr = uint8VerStr / 4;
  27081. var uint8EleOffset = element._offset;
  27082. var floatEleOffset = uint8EleOffset / 4;
  27083. switch (elementUsage) {
  27084. case VertexMesh.MESH_TEXTURECOORDINATE0:
  27085. case VertexMesh.MESH_TEXTURECOORDINATE1:
  27086. for (var i = 0; i < this._vertexCount; i++) {
  27087. var offset = floatVerStr * i + floatEleOffset;
  27088. data[i] = new Vector2(floatVertices[offset], floatVertices[offset + 1]);
  27089. }
  27090. break;
  27091. case VertexMesh.MESH_POSITION0:
  27092. case VertexMesh.MESH_NORMAL0:
  27093. for (var i = 0; i < this._vertexCount; i++) {
  27094. var offset = floatVerStr * i + floatEleOffset;
  27095. data[i] = new Vector3(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2]);
  27096. }
  27097. break;
  27098. case VertexMesh.MESH_TANGENT0:
  27099. case VertexMesh.MESH_BLENDWEIGHT0:
  27100. for (var i = 0; i < this._vertexCount; i++) {
  27101. var offset = floatVerStr * i + floatEleOffset;
  27102. data[i] = new Vector4(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2], floatVertices[offset + 3]);
  27103. }
  27104. break;
  27105. case VertexMesh.MESH_COLOR0:
  27106. for (var i = 0; i < this._vertexCount; i++) {
  27107. var offset = floatVerStr * i + floatEleOffset;
  27108. data[i] = new Color(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2], floatVertices[offset + 3]);
  27109. }
  27110. break;
  27111. case VertexMesh.MESH_BLENDINDICES0:
  27112. for (var i = 0; i < this._vertexCount; i++) {
  27113. var offset = uint8VerStr * i + uint8EleOffset;
  27114. data[i] = new Vector4(uint8Vertices[offset], uint8Vertices[offset + 1], uint8Vertices[offset + 2], uint8Vertices[offset + 3]);
  27115. }
  27116. break;
  27117. default:
  27118. throw "Mesh:Unknown elementUsage.";
  27119. }
  27120. }
  27121. }
  27122. _setVerticeElementData(data, elementUsage) {
  27123. var verDec = this._vertexBuffer.vertexDeclaration;
  27124. var element = verDec.getVertexElementByUsage(elementUsage);
  27125. if (element) {
  27126. var uint8Vertices = this._vertexBuffer.getUint8Data();
  27127. var floatVertices = this._vertexBuffer.getFloat32Data();
  27128. var uint8VerStr = verDec.vertexStride;
  27129. var float8VerStr = uint8VerStr / 4;
  27130. var uint8EleOffset = element._offset;
  27131. var floatEleOffset = uint8EleOffset / 4;
  27132. switch (elementUsage) {
  27133. case VertexMesh.MESH_TEXTURECOORDINATE0:
  27134. case VertexMesh.MESH_TEXTURECOORDINATE1:
  27135. for (var i = 0, n = data.length; i < n; i++) {
  27136. var offset = float8VerStr * i + floatEleOffset;
  27137. var vec2 = data[i];
  27138. floatVertices[offset] = vec2.x;
  27139. floatVertices[offset + 1] = vec2.y;
  27140. }
  27141. break;
  27142. case VertexMesh.MESH_POSITION0:
  27143. case VertexMesh.MESH_NORMAL0:
  27144. for (var i = 0, n = data.length; i < n; i++) {
  27145. var offset = float8VerStr * i + floatEleOffset;
  27146. var vec3 = data[i];
  27147. floatVertices[offset] = vec3.x;
  27148. floatVertices[offset + 1] = vec3.y;
  27149. floatVertices[offset + 2] = vec3.z;
  27150. }
  27151. break;
  27152. case VertexMesh.MESH_TANGENT0:
  27153. case VertexMesh.MESH_BLENDWEIGHT0:
  27154. for (var i = 0, n = data.length; i < n; i++) {
  27155. var offset = float8VerStr * i + floatEleOffset;
  27156. var vec4 = data[i];
  27157. floatVertices[offset] = vec4.x;
  27158. floatVertices[offset + 1] = vec4.y;
  27159. floatVertices[offset + 2] = vec4.z;
  27160. floatVertices[offset + 3] = vec4.w;
  27161. }
  27162. break;
  27163. case VertexMesh.MESH_COLOR0:
  27164. for (var i = 0, n = data.length; i < n; i++) {
  27165. var offset = float8VerStr * i + floatEleOffset;
  27166. var cor = data[i];
  27167. floatVertices[offset] = cor.r;
  27168. floatVertices[offset + 1] = cor.g;
  27169. floatVertices[offset + 2] = cor.b;
  27170. floatVertices[offset + 2] = cor.a;
  27171. }
  27172. break;
  27173. case VertexMesh.MESH_BLENDINDICES0:
  27174. for (var i = 0, n = data.length; i < n; i++) {
  27175. var offset = uint8VerStr * i + uint8EleOffset;
  27176. var vec4 = data[i];
  27177. uint8Vertices[offset] = vec4.x;
  27178. uint8Vertices[offset + 1] = vec4.y;
  27179. uint8Vertices[offset + 2] = vec4.z;
  27180. uint8Vertices[offset + 3] = vec4.w;
  27181. }
  27182. break;
  27183. default:
  27184. throw "Mesh:Unknown elementUsage.";
  27185. }
  27186. this._minVerticesUpdate = 0;
  27187. this._maxVerticesUpdate = Number.MAX_SAFE_INTEGER;
  27188. }
  27189. else {
  27190. console.warn("Mesh: the mesh don't have this VertexElement.");
  27191. }
  27192. }
  27193. _disposeResource() {
  27194. for (var i = 0, n = this._subMeshes.length; i < n; i++)
  27195. this._subMeshes[i].destroy();
  27196. this._nativeTriangleMesh && window.Physics3D.destroy(this._nativeTriangleMesh);
  27197. this._vertexBuffer.destroy();
  27198. this._indexBuffer.destroy();
  27199. this._setCPUMemory(0);
  27200. this._setGPUMemory(0);
  27201. this._bufferState.destroy();
  27202. this._instanceBufferState.destroy();
  27203. this._bufferState = null;
  27204. this._instanceBufferState = null;
  27205. this._vertexBuffer = null;
  27206. this._indexBuffer = null;
  27207. this._subMeshes = null;
  27208. this._nativeTriangleMesh = null;
  27209. this._indexBuffer = null;
  27210. this._boneNames = null;
  27211. this._inverseBindPoses = null;
  27212. }
  27213. _setSubMeshes(subMeshes) {
  27214. this._subMeshes = subMeshes;
  27215. for (var i = 0, n = subMeshes.length; i < n; i++)
  27216. subMeshes[i]._indexInMesh = i;
  27217. this.calculateBounds();
  27218. }
  27219. _setBuffer(vertexBuffer, indexBuffer) {
  27220. var bufferState = this._bufferState;
  27221. bufferState.bind();
  27222. bufferState.applyVertexBuffer(vertexBuffer);
  27223. bufferState.applyIndexBuffer(indexBuffer);
  27224. bufferState.unBind();
  27225. var instanceBufferState = this._instanceBufferState;
  27226. instanceBufferState.bind();
  27227. instanceBufferState.applyVertexBuffer(vertexBuffer);
  27228. instanceBufferState.applyInstanceVertexBuffer(SubMeshInstanceBatch.instance.instanceWorldMatrixBuffer);
  27229. instanceBufferState.applyInstanceVertexBuffer(SubMeshInstanceBatch.instance.instanceMVPMatrixBuffer);
  27230. instanceBufferState.applyIndexBuffer(indexBuffer);
  27231. instanceBufferState.unBind();
  27232. }
  27233. _getPhysicMesh() {
  27234. if (!this._nativeTriangleMesh) {
  27235. var physics3D = window.Physics3D;
  27236. var triangleMesh = new physics3D.btTriangleMesh();
  27237. var nativePositio0 = Mesh._nativeTempVector30;
  27238. var nativePositio1 = Mesh._nativeTempVector31;
  27239. var nativePositio2 = Mesh._nativeTempVector32;
  27240. var position0 = this._tempVector30;
  27241. var position1 = this._tempVector31;
  27242. var position2 = this._tempVector32;
  27243. var vertexBuffer = this._vertexBuffer;
  27244. var positionElement = this._getPositionElement(vertexBuffer);
  27245. var verticesData = vertexBuffer.getFloat32Data();
  27246. var floatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  27247. var posOffset = positionElement._offset / 4;
  27248. var indices = this._indexBuffer.getData();
  27249. for (var i = 0, n = indices.length; i < n; i += 3) {
  27250. var p0Index = indices[i] * floatCount + posOffset;
  27251. var p1Index = indices[i + 1] * floatCount + posOffset;
  27252. var p2Index = indices[i + 2] * floatCount + posOffset;
  27253. position0.setValue(verticesData[p0Index], verticesData[p0Index + 1], verticesData[p0Index + 2]);
  27254. position1.setValue(verticesData[p1Index], verticesData[p1Index + 1], verticesData[p1Index + 2]);
  27255. position2.setValue(verticesData[p2Index], verticesData[p2Index + 1], verticesData[p2Index + 2]);
  27256. Utils3D._convertToBulletVec3(position0, nativePositio0, true);
  27257. Utils3D._convertToBulletVec3(position1, nativePositio1, true);
  27258. Utils3D._convertToBulletVec3(position2, nativePositio2, true);
  27259. triangleMesh.addTriangle(nativePositio0, nativePositio1, nativePositio2, true);
  27260. }
  27261. this._nativeTriangleMesh = triangleMesh;
  27262. }
  27263. return this._nativeTriangleMesh;
  27264. }
  27265. _uploadVerticesData() {
  27266. var min = this._minVerticesUpdate;
  27267. var max = this._maxVerticesUpdate;
  27268. if (min !== -1 && max !== -1) {
  27269. var offset = min;
  27270. this._vertexBuffer.setData(this._vertexBuffer.getUint8Data().buffer, offset, offset, max - min);
  27271. this._minVerticesUpdate = -1;
  27272. this._maxVerticesUpdate = -1;
  27273. }
  27274. }
  27275. getSubMesh(index) {
  27276. return this._subMeshes[index];
  27277. }
  27278. getPositions(positions) {
  27279. if (this._isReadable)
  27280. this._getVerticeElementData(positions, VertexMesh.MESH_POSITION0);
  27281. else
  27282. throw "Mesh:can't get positions on mesh,isReadable must be true.";
  27283. }
  27284. setPositions(positions) {
  27285. if (this._isReadable) {
  27286. this._setVerticeElementData(positions, VertexMesh.MESH_POSITION0);
  27287. this._needUpdateBounds = true;
  27288. }
  27289. else {
  27290. throw "Mesh:setPosition() need isReadable must be true or use setVertices().";
  27291. }
  27292. }
  27293. getColors(colors) {
  27294. if (this._isReadable)
  27295. this._getVerticeElementData(colors, VertexMesh.MESH_COLOR0);
  27296. else
  27297. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  27298. }
  27299. setColors(colors) {
  27300. if (this._isReadable)
  27301. this._setVerticeElementData(colors, VertexMesh.MESH_COLOR0);
  27302. else
  27303. throw "Mesh:setColors() need isReadable must be true or use setVertices().";
  27304. }
  27305. getUVs(uvs, channel = 0) {
  27306. if (this._isReadable) {
  27307. switch (channel) {
  27308. case 0:
  27309. this._getVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE0);
  27310. break;
  27311. case 1:
  27312. this._getVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE1);
  27313. break;
  27314. default:
  27315. throw "Mesh:Invalid channel.";
  27316. }
  27317. }
  27318. else {
  27319. throw "Mesh:can't get uvs on mesh,isReadable must be true.";
  27320. }
  27321. }
  27322. setUVs(uvs, channel = 0) {
  27323. if (this._isReadable) {
  27324. switch (channel) {
  27325. case 0:
  27326. this._setVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE0);
  27327. break;
  27328. case 1:
  27329. this._setVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE1);
  27330. break;
  27331. default:
  27332. throw "Mesh:Invalid channel.";
  27333. }
  27334. }
  27335. else {
  27336. throw "Mesh:setUVs() need isReadable must be true or use setVertices().";
  27337. }
  27338. }
  27339. getNormals(normals) {
  27340. if (this._isReadable)
  27341. this._getVerticeElementData(normals, VertexMesh.MESH_NORMAL0);
  27342. else
  27343. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  27344. }
  27345. setNormals(normals) {
  27346. if (this._isReadable)
  27347. this._setVerticeElementData(normals, VertexMesh.MESH_NORMAL0);
  27348. else
  27349. throw "Mesh:setNormals() need must be true or use setVertices().";
  27350. }
  27351. getTangents(tangents) {
  27352. if (this._isReadable)
  27353. this._getVerticeElementData(tangents, VertexMesh.MESH_TANGENT0);
  27354. else
  27355. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  27356. }
  27357. setTangents(tangents) {
  27358. if (this._isReadable)
  27359. this._setVerticeElementData(tangents, VertexMesh.MESH_TANGENT0);
  27360. else
  27361. throw "Mesh:setTangents() need isReadable must be true or use setVertices().";
  27362. }
  27363. getBoneWeights(boneWeights) {
  27364. if (this._isReadable)
  27365. this._getVerticeElementData(boneWeights, VertexMesh.MESH_BLENDWEIGHT0);
  27366. else
  27367. throw "Mesh:can't get boneWeights on mesh,isReadable must be true.";
  27368. }
  27369. setBoneWeights(boneWeights) {
  27370. if (this._isReadable)
  27371. this._setVerticeElementData(boneWeights, VertexMesh.MESH_BLENDWEIGHT0);
  27372. else
  27373. throw "Mesh:setBoneWeights() need isReadable must be true or use setVertices().";
  27374. }
  27375. getBoneIndices(boneIndices) {
  27376. if (this._isReadable)
  27377. this._getVerticeElementData(boneIndices, VertexMesh.MESH_BLENDINDICES0);
  27378. else
  27379. throw "Mesh:can't get boneIndices on mesh,isReadable must be true.";
  27380. }
  27381. setBoneIndices(boneIndices) {
  27382. if (this._isReadable)
  27383. this._setVerticeElementData(boneIndices, VertexMesh.MESH_BLENDINDICES0);
  27384. else
  27385. throw "Mesh:setBoneIndices() need isReadable must be true or use setVertices().";
  27386. }
  27387. markAsUnreadbale() {
  27388. this._uploadVerticesData();
  27389. this._vertexBuffer.markAsUnreadbale();
  27390. this._isReadable = false;
  27391. }
  27392. getVertexDeclaration() {
  27393. return this._vertexBuffer._vertexDeclaration;
  27394. }
  27395. getVertices() {
  27396. if (this._isReadable)
  27397. return this._vertexBuffer.getUint8Data().buffer.slice(0);
  27398. else
  27399. throw "Mesh:can't get vertices on mesh,isReadable must be true.";
  27400. }
  27401. setVertices(vertices) {
  27402. this._vertexBuffer.setData(vertices);
  27403. this._needUpdateBounds = true;
  27404. }
  27405. getIndices() {
  27406. if (this._isReadable)
  27407. return this._indexBuffer.getData().slice();
  27408. else
  27409. throw "Mesh:can't get indices on subMesh,mesh's isReadable must be true.";
  27410. }
  27411. setIndices(indices) {
  27412. this._indexBuffer.setData(indices);
  27413. }
  27414. calculateBounds() {
  27415. if (this._isReadable) {
  27416. if (this._needUpdateBounds) {
  27417. var min = this._tempVector30;
  27418. var max = this._tempVector31;
  27419. min.x = min.y = min.z = Number.MAX_VALUE;
  27420. max.x = max.y = max.z = -Number.MAX_VALUE;
  27421. var vertexBuffer = this._vertexBuffer;
  27422. var positionElement = this._getPositionElement(vertexBuffer);
  27423. var verticesData = vertexBuffer.getFloat32Data();
  27424. var floatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  27425. var posOffset = positionElement._offset / 4;
  27426. for (var j = 0, m = verticesData.length; j < m; j += floatCount) {
  27427. var ofset = j + posOffset;
  27428. var pX = verticesData[ofset];
  27429. var pY = verticesData[ofset + 1];
  27430. var pZ = verticesData[ofset + 2];
  27431. min.x = Math.min(min.x, pX);
  27432. min.y = Math.min(min.y, pY);
  27433. min.z = Math.min(min.z, pZ);
  27434. max.x = Math.max(max.x, pX);
  27435. max.y = Math.max(max.y, pY);
  27436. max.z = Math.max(max.z, pZ);
  27437. }
  27438. this._bounds.setMin(min);
  27439. this._bounds.setMax(max);
  27440. this._needUpdateBounds = false;
  27441. }
  27442. }
  27443. else {
  27444. throw "Mesh:can't calculate bounds on subMesh,mesh's isReadable must be true.";
  27445. }
  27446. }
  27447. cloneTo(destObject) {
  27448. var destMesh = destObject;
  27449. var vb = this._vertexBuffer;
  27450. var destVB = new VertexBuffer3D(vb._byteLength, vb.bufferUsage, vb.canRead);
  27451. destVB.vertexDeclaration = vb.vertexDeclaration;
  27452. destVB.setData(vb.getUint8Data().slice().buffer);
  27453. destMesh._vertexBuffer = destVB;
  27454. destMesh._vertexCount = this._vertexCount;
  27455. var ib = this._indexBuffer;
  27456. var destIB = new IndexBuffer3D(IndexBuffer3D.INDEXTYPE_USHORT, ib.indexCount, ib.bufferUsage, ib.canRead);
  27457. destIB.setData(ib.getData().slice());
  27458. destMesh._indexBuffer = destIB;
  27459. destMesh._setBuffer(destMesh._vertexBuffer, destIB);
  27460. destMesh._setCPUMemory(this.cpuMemory);
  27461. destMesh._setGPUMemory(this.gpuMemory);
  27462. var i;
  27463. var boneNames = this._boneNames;
  27464. var destBoneNames = destMesh._boneNames = [];
  27465. for (i = 0; i < boneNames.length; i++)
  27466. destBoneNames[i] = boneNames[i];
  27467. var inverseBindPoses = this._inverseBindPoses;
  27468. var destInverseBindPoses = destMesh._inverseBindPoses = [];
  27469. for (i = 0; i < inverseBindPoses.length; i++)
  27470. destInverseBindPoses[i] = inverseBindPoses[i];
  27471. destMesh._bindPoseIndices = new Uint16Array(this._bindPoseIndices);
  27472. for (i = 0; i < this._skinDataPathMarks.length; i++)
  27473. destMesh._skinDataPathMarks[i] = this._skinDataPathMarks[i].slice();
  27474. for (i = 0; i < this.subMeshCount; i++) {
  27475. var subMesh = this._subMeshes[i];
  27476. var subIndexBufferStart = subMesh._subIndexBufferStart;
  27477. var subIndexBufferCount = subMesh._subIndexBufferCount;
  27478. var boneIndicesList = subMesh._boneIndicesList;
  27479. var destSubmesh = new SubMesh(destMesh);
  27480. destSubmesh._subIndexBufferStart.length = subIndexBufferStart.length;
  27481. destSubmesh._subIndexBufferCount.length = subIndexBufferCount.length;
  27482. destSubmesh._boneIndicesList.length = boneIndicesList.length;
  27483. for (var j = 0; j < subIndexBufferStart.length; j++)
  27484. destSubmesh._subIndexBufferStart[j] = subIndexBufferStart[j];
  27485. for (j = 0; j < subIndexBufferCount.length; j++)
  27486. destSubmesh._subIndexBufferCount[j] = subIndexBufferCount[j];
  27487. for (j = 0; j < boneIndicesList.length; j++)
  27488. destSubmesh._boneIndicesList[j] = new Uint16Array(boneIndicesList[j]);
  27489. destSubmesh._indexBuffer = destIB;
  27490. destSubmesh._indexStart = subMesh._indexStart;
  27491. destSubmesh._indexCount = subMesh._indexCount;
  27492. destSubmesh._indices = new Uint16Array(destIB.getData().buffer, subMesh._indexStart * 2, subMesh._indexCount);
  27493. var vertexBuffer = destMesh._vertexBuffer;
  27494. destSubmesh._vertexBuffer = vertexBuffer;
  27495. destMesh._subMeshes.push(destSubmesh);
  27496. }
  27497. destMesh._setSubMeshes(destMesh._subMeshes);
  27498. }
  27499. clone() {
  27500. var dest = new Mesh();
  27501. this.cloneTo(dest);
  27502. return dest;
  27503. }
  27504. }
  27505. Mesh.MESH = "MESH";
  27506. class PrimitiveMesh {
  27507. static __init__() {
  27508. }
  27509. static _createMesh(vertexDeclaration, vertices, indices) {
  27510. var gl = Laya.LayaGL.instance;
  27511. var mesh = new Mesh();
  27512. var subMesh = new SubMesh(mesh);
  27513. var vertexBuffer = new VertexBuffer3D(vertices.length * 4, gl.STATIC_DRAW, true);
  27514. vertexBuffer.vertexDeclaration = vertexDeclaration;
  27515. vertexBuffer.setData(vertices.buffer);
  27516. mesh._vertexBuffer = vertexBuffer;
  27517. mesh._vertexCount = vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  27518. var indexBuffer = new IndexBuffer3D(IndexBuffer3D.INDEXTYPE_USHORT, indices.length, gl.STATIC_DRAW, true);
  27519. indexBuffer.setData(indices);
  27520. mesh._indexBuffer = indexBuffer;
  27521. mesh._setBuffer(vertexBuffer, indexBuffer);
  27522. subMesh._vertexBuffer = vertexBuffer;
  27523. subMesh._indexBuffer = indexBuffer;
  27524. subMesh._setIndexRange(0, indexBuffer.indexCount);
  27525. var subIndexBufferStart = subMesh._subIndexBufferStart;
  27526. var subIndexBufferCount = subMesh._subIndexBufferCount;
  27527. var boneIndicesList = subMesh._boneIndicesList;
  27528. subIndexBufferStart.length = 1;
  27529. subIndexBufferCount.length = 1;
  27530. boneIndicesList.length = 1;
  27531. subIndexBufferStart[0] = 0;
  27532. subIndexBufferCount[0] = indexBuffer.indexCount;
  27533. var subMeshes = [];
  27534. subMeshes.push(subMesh);
  27535. mesh._setSubMeshes(subMeshes);
  27536. var memorySize = vertexBuffer._byteLength + indexBuffer._byteLength;
  27537. mesh._setCPUMemory(memorySize);
  27538. mesh._setGPUMemory(memorySize);
  27539. return mesh;
  27540. }
  27541. static createBox(long = 1, height = 1, width = 1) {
  27542. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  27543. var halfLong = long / 2;
  27544. var halfHeight = height / 2;
  27545. var halfWidth = width / 2;
  27546. var vertices = new Float32Array([
  27547. -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,
  27548. -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,
  27549. -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,
  27550. 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,
  27551. -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,
  27552. -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
  27553. ]);
  27554. var indices = new Uint16Array([
  27555. 0, 1, 2, 2, 3, 0,
  27556. 4, 7, 6, 6, 5, 4,
  27557. 8, 9, 10, 10, 11, 8,
  27558. 12, 15, 14, 14, 13, 12,
  27559. 16, 17, 18, 18, 19, 16,
  27560. 20, 23, 22, 22, 21, 20
  27561. ]);
  27562. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  27563. }
  27564. static createCapsule(radius = 0.5, height = 2, stacks = 16, slices = 32) {
  27565. var vertexCount = (stacks + 1) * (slices + 1) * 2 + (slices + 1) * 2;
  27566. var indexCount = (3 * stacks * (slices + 1)) * 2 * 2 + 2 * slices * 3;
  27567. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  27568. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  27569. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  27570. var indices = new Uint16Array(indexCount);
  27571. var stackAngle = (Math.PI / 2.0) / stacks;
  27572. var sliceAngle = (Math.PI * 2.0) / slices;
  27573. var hcHeight = height / 2 - radius;
  27574. var posX = 0;
  27575. var posY = 0;
  27576. var posZ = 0;
  27577. var vc = 0;
  27578. var ic = 0;
  27579. var verticeCount = 0;
  27580. var stack, slice;
  27581. for (stack = 0; stack <= stacks; stack++) {
  27582. for (slice = 0; slice <= slices; slice++) {
  27583. posX = radius * Math.cos(stack * stackAngle) * Math.cos(slice * sliceAngle + Math.PI);
  27584. posY = radius * Math.sin(stack * stackAngle);
  27585. posZ = radius * Math.cos(stack * stackAngle) * Math.sin(slice * sliceAngle + Math.PI);
  27586. vertices[vc++] = posX;
  27587. vertices[vc++] = posY + hcHeight;
  27588. vertices[vc++] = posZ;
  27589. vertices[vc++] = posX;
  27590. vertices[vc++] = posY;
  27591. vertices[vc++] = posZ;
  27592. vertices[vc++] = 1 - slice / slices;
  27593. vertices[vc++] = (1 - stack / stacks) * ((Math.PI * radius / 2) / (height + Math.PI * radius));
  27594. if (stack < stacks) {
  27595. indices[ic++] = (stack * (slices + 1)) + slice + (slices + 1);
  27596. indices[ic++] = (stack * (slices + 1)) + slice;
  27597. indices[ic++] = (stack * (slices + 1)) + slice + 1;
  27598. indices[ic++] = (stack * (slices + 1)) + slice + (slices);
  27599. indices[ic++] = (stack * (slices + 1)) + slice;
  27600. indices[ic++] = (stack * (slices + 1)) + slice + (slices + 1);
  27601. }
  27602. }
  27603. }
  27604. verticeCount += (stacks + 1) * (slices + 1);
  27605. for (stack = 0; stack <= stacks; stack++) {
  27606. for (slice = 0; slice <= slices; slice++) {
  27607. posX = radius * Math.cos(stack * stackAngle) * Math.cos(slice * sliceAngle + Math.PI);
  27608. posY = radius * Math.sin(-stack * stackAngle);
  27609. posZ = radius * Math.cos(stack * stackAngle) * Math.sin(slice * sliceAngle + Math.PI);
  27610. vertices[vc++] = posX;
  27611. vertices[vc++] = posY - hcHeight;
  27612. vertices[vc++] = posZ;
  27613. vertices[vc++] = posX;
  27614. vertices[vc++] = posY;
  27615. vertices[vc++] = posZ;
  27616. vertices[vc++] = 1 - slice / slices;
  27617. vertices[vc++] = ((stack / stacks) * (Math.PI * radius / 2) + (height + Math.PI * radius / 2)) / (height + Math.PI * radius);
  27618. if (stack < stacks) {
  27619. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice;
  27620. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices + 1);
  27621. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + 1;
  27622. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice;
  27623. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices);
  27624. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices + 1);
  27625. }
  27626. }
  27627. }
  27628. verticeCount += (stacks + 1) * (slices + 1);
  27629. for (slice = 0; slice <= slices; slice++) {
  27630. posX = radius * Math.cos(slice * sliceAngle + Math.PI);
  27631. posY = hcHeight;
  27632. posZ = radius * Math.sin(slice * sliceAngle + Math.PI);
  27633. vertices[vc++] = posX;
  27634. vertices[vc + (slices + 1) * 8 - 1] = posX;
  27635. vertices[vc++] = posY;
  27636. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  27637. vertices[vc++] = posZ;
  27638. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  27639. vertices[vc++] = posX;
  27640. vertices[vc + (slices + 1) * 8 - 1] = posX;
  27641. vertices[vc++] = 0;
  27642. vertices[vc + (slices + 1) * 8 - 1] = 0;
  27643. vertices[vc++] = posZ;
  27644. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  27645. vertices[vc++] = 1 - slice * 1 / slices;
  27646. vertices[vc + (slices + 1) * 8 - 1] = 1 - slice * 1 / slices;
  27647. vertices[vc++] = (Math.PI * radius / 2) / (height + Math.PI * radius);
  27648. vertices[vc + (slices + 1) * 8 - 1] = (Math.PI * radius / 2 + height) / (height + Math.PI * radius);
  27649. }
  27650. for (slice = 0; slice < slices; slice++) {
  27651. indices[ic++] = slice + verticeCount + (slices + 1);
  27652. indices[ic++] = slice + verticeCount + 1;
  27653. indices[ic++] = slice + verticeCount;
  27654. indices[ic++] = slice + verticeCount + (slices + 1);
  27655. indices[ic++] = slice + verticeCount + (slices + 1) + 1;
  27656. indices[ic++] = slice + verticeCount + 1;
  27657. }
  27658. verticeCount += 2 * (slices + 1);
  27659. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  27660. }
  27661. static createCone(radius = 0.5, height = 1, slices = 32) {
  27662. var vertexCount = (slices + 1 + 1) + (slices + 1) * 2;
  27663. var indexCount = 6 * slices + 3 * slices;
  27664. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  27665. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  27666. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  27667. var indices = new Uint16Array(indexCount);
  27668. var sliceAngle = (Math.PI * 2.0) / slices;
  27669. var halfHeight = height / 2;
  27670. var curAngle = 0;
  27671. var verticeCount = 0;
  27672. var posX = 0;
  27673. var posY = 0;
  27674. var posZ = 0;
  27675. var normal = new Vector3();
  27676. var downV3 = new Vector3(0, -1, 0);
  27677. var upPoint = new Vector3(0, halfHeight, 0);
  27678. var downPoint = new Vector3();
  27679. var v3 = new Vector3();
  27680. var q4 = new Quaternion();
  27681. var rotateAxis = new Vector3();
  27682. var rotateRadius;
  27683. var vc = 0;
  27684. var ic = 0;
  27685. for (var rv = 0; rv <= slices; rv++) {
  27686. curAngle = rv * sliceAngle;
  27687. posX = Math.cos(curAngle + Math.PI) * radius;
  27688. posY = halfHeight;
  27689. posZ = Math.sin(curAngle + Math.PI) * radius;
  27690. vertices[vc++] = 0;
  27691. vertices[vc + (slices + 1) * 8 - 1] = posX;
  27692. vertices[vc++] = posY;
  27693. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  27694. vertices[vc++] = 0;
  27695. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  27696. normal.x = posX;
  27697. normal.y = 0;
  27698. normal.z = posZ;
  27699. downPoint.x = posX;
  27700. downPoint.y = -posY;
  27701. downPoint.z = posZ;
  27702. Vector3.subtract(downPoint, upPoint, v3);
  27703. Vector3.normalize(v3, v3);
  27704. rotateRadius = Math.acos(Vector3.dot(downV3, v3));
  27705. Vector3.cross(downV3, v3, rotateAxis);
  27706. Vector3.normalize(rotateAxis, rotateAxis);
  27707. Quaternion.createFromAxisAngle(rotateAxis, rotateRadius, q4);
  27708. Vector3.normalize(normal, normal);
  27709. Vector3.transformQuat(normal, q4, normal);
  27710. Vector3.normalize(normal, normal);
  27711. vertices[vc++] = normal.x;
  27712. vertices[vc + (slices + 1) * 8 - 1] = normal.x;
  27713. vertices[vc++] = normal.y;
  27714. vertices[vc + (slices + 1) * 8 - 1] = normal.y;
  27715. vertices[vc++] = normal.z;
  27716. vertices[vc + (slices + 1) * 8 - 1] = normal.z;
  27717. vertices[vc++] = 1 - rv * 1 / slices;
  27718. vertices[vc + (slices + 1) * 8 - 1] = 1 - rv * 1 / slices;
  27719. vertices[vc++] = 0;
  27720. vertices[vc + (slices + 1) * 8 - 1] = 1;
  27721. }
  27722. vc += (slices + 1) * 8;
  27723. for (var ri = 0; ri < slices; ri++) {
  27724. indices[ic++] = ri + verticeCount + (slices + 1);
  27725. indices[ic++] = ri + verticeCount + 1;
  27726. indices[ic++] = ri + verticeCount;
  27727. indices[ic++] = ri + verticeCount + (slices + 1);
  27728. indices[ic++] = ri + verticeCount + (slices + 1) + 1;
  27729. indices[ic++] = ri + verticeCount + 1;
  27730. }
  27731. verticeCount += 2 * (slices + 1);
  27732. for (var bv = 0; bv <= slices; bv++) {
  27733. if (bv === 0) {
  27734. vertices[vc++] = 0;
  27735. vertices[vc++] = -halfHeight;
  27736. vertices[vc++] = 0;
  27737. vertices[vc++] = 0;
  27738. vertices[vc++] = -1;
  27739. vertices[vc++] = 0;
  27740. vertices[vc++] = 0.5;
  27741. vertices[vc++] = 0.5;
  27742. }
  27743. curAngle = bv * sliceAngle;
  27744. posX = Math.cos(curAngle + Math.PI) * radius;
  27745. posY = -halfHeight;
  27746. posZ = Math.sin(curAngle + Math.PI) * radius;
  27747. vertices[vc++] = posX;
  27748. vertices[vc++] = posY;
  27749. vertices[vc++] = posZ;
  27750. vertices[vc++] = 0;
  27751. vertices[vc++] = -1;
  27752. vertices[vc++] = 0;
  27753. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  27754. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  27755. }
  27756. for (var bi = 0; bi < slices; bi++) {
  27757. indices[ic++] = 0 + verticeCount;
  27758. indices[ic++] = bi + 2 + verticeCount;
  27759. indices[ic++] = bi + 1 + verticeCount;
  27760. }
  27761. verticeCount += slices + 1 + 1;
  27762. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  27763. }
  27764. static createCylinder(radius = 0.5, height = 2, slices = 32) {
  27765. var vertexCount = (slices + 1 + 1) + (slices + 1) * 2 + (slices + 1 + 1);
  27766. var indexCount = 3 * slices + 6 * slices + 3 * slices;
  27767. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  27768. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  27769. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  27770. var indices = new Uint16Array(indexCount);
  27771. var sliceAngle = (Math.PI * 2.0) / slices;
  27772. var halfHeight = height / 2;
  27773. var curAngle = 0;
  27774. var verticeCount = 0;
  27775. var posX = 0;
  27776. var posY = 0;
  27777. var posZ = 0;
  27778. var vc = 0;
  27779. var ic = 0;
  27780. for (var tv = 0; tv <= slices; tv++) {
  27781. if (tv === 0) {
  27782. vertices[vc++] = 0;
  27783. vertices[vc++] = halfHeight;
  27784. vertices[vc++] = 0;
  27785. vertices[vc++] = 0;
  27786. vertices[vc++] = 1;
  27787. vertices[vc++] = 0;
  27788. vertices[vc++] = 0.5;
  27789. vertices[vc++] = 0.5;
  27790. }
  27791. curAngle = tv * sliceAngle;
  27792. posX = Math.cos(curAngle) * radius;
  27793. posY = halfHeight;
  27794. posZ = Math.sin(curAngle) * radius;
  27795. vertices[vc++] = posX;
  27796. vertices[vc++] = posY;
  27797. vertices[vc++] = posZ;
  27798. vertices[vc++] = 0;
  27799. vertices[vc++] = 1;
  27800. vertices[vc++] = 0;
  27801. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  27802. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  27803. }
  27804. for (var ti = 0; ti < slices; ti++) {
  27805. indices[ic++] = 0;
  27806. indices[ic++] = ti + 1;
  27807. indices[ic++] = ti + 2;
  27808. }
  27809. verticeCount += slices + 1 + 1;
  27810. for (var rv = 0; rv <= slices; rv++) {
  27811. curAngle = rv * sliceAngle;
  27812. posX = Math.cos(curAngle + Math.PI) * radius;
  27813. posY = halfHeight;
  27814. posZ = Math.sin(curAngle + Math.PI) * radius;
  27815. vertices[vc++] = posX;
  27816. vertices[vc + (slices + 1) * 8 - 1] = posX;
  27817. vertices[vc++] = posY;
  27818. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  27819. vertices[vc++] = posZ;
  27820. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  27821. vertices[vc++] = posX;
  27822. vertices[vc + (slices + 1) * 8 - 1] = posX;
  27823. vertices[vc++] = 0;
  27824. vertices[vc + (slices + 1) * 8 - 1] = 0;
  27825. vertices[vc++] = posZ;
  27826. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  27827. vertices[vc++] = 1 - rv * 1 / slices;
  27828. vertices[vc + (slices + 1) * 8 - 1] = 1 - rv * 1 / slices;
  27829. vertices[vc++] = 0;
  27830. vertices[vc + (slices + 1) * 8 - 1] = 1;
  27831. }
  27832. vc += (slices + 1) * 8;
  27833. for (var ri = 0; ri < slices; ri++) {
  27834. indices[ic++] = ri + verticeCount + (slices + 1);
  27835. indices[ic++] = ri + verticeCount + 1;
  27836. indices[ic++] = ri + verticeCount;
  27837. indices[ic++] = ri + verticeCount + (slices + 1);
  27838. indices[ic++] = ri + verticeCount + (slices + 1) + 1;
  27839. indices[ic++] = ri + verticeCount + 1;
  27840. }
  27841. verticeCount += 2 * (slices + 1);
  27842. for (var bv = 0; bv <= slices; bv++) {
  27843. if (bv === 0) {
  27844. vertices[vc++] = 0;
  27845. vertices[vc++] = -halfHeight;
  27846. vertices[vc++] = 0;
  27847. vertices[vc++] = 0;
  27848. vertices[vc++] = -1;
  27849. vertices[vc++] = 0;
  27850. vertices[vc++] = 0.5;
  27851. vertices[vc++] = 0.5;
  27852. }
  27853. curAngle = bv * sliceAngle;
  27854. posX = Math.cos(curAngle + Math.PI) * radius;
  27855. posY = -halfHeight;
  27856. posZ = Math.sin(curAngle + Math.PI) * radius;
  27857. vertices[vc++] = posX;
  27858. vertices[vc++] = posY;
  27859. vertices[vc++] = posZ;
  27860. vertices[vc++] = 0;
  27861. vertices[vc++] = -1;
  27862. vertices[vc++] = 0;
  27863. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  27864. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  27865. }
  27866. for (var bi = 0; bi < slices; bi++) {
  27867. indices[ic++] = 0 + verticeCount;
  27868. indices[ic++] = bi + 2 + verticeCount;
  27869. indices[ic++] = bi + 1 + verticeCount;
  27870. }
  27871. verticeCount += slices + 1 + 1;
  27872. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  27873. }
  27874. static createPlane(long = 10, width = 10, stacks = 10, slices = 10) {
  27875. var vertexCount = (stacks + 1) * (slices + 1);
  27876. var indexCount = stacks * slices * 2 * 3;
  27877. var indices = new Uint16Array(indexCount);
  27878. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  27879. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  27880. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  27881. var halfLong = long / 2;
  27882. var halfWidth = width / 2;
  27883. var stacksLong = long / stacks;
  27884. var slicesWidth = width / slices;
  27885. var verticeCount = 0;
  27886. for (var i = 0; i <= slices; i++) {
  27887. for (var j = 0; j <= stacks; j++) {
  27888. vertices[verticeCount++] = j * stacksLong - halfLong;
  27889. vertices[verticeCount++] = 0;
  27890. vertices[verticeCount++] = i * slicesWidth - halfWidth;
  27891. vertices[verticeCount++] = 0;
  27892. vertices[verticeCount++] = 1;
  27893. vertices[verticeCount++] = 0;
  27894. vertices[verticeCount++] = j * 1 / stacks;
  27895. vertices[verticeCount++] = i * 1 / slices;
  27896. }
  27897. }
  27898. var indiceIndex = 0;
  27899. for (i = 0; i < slices; i++) {
  27900. for (j = 0; j < stacks; j++) {
  27901. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j;
  27902. indices[indiceIndex++] = i * (stacks + 1) + j;
  27903. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j + 1;
  27904. indices[indiceIndex++] = i * (stacks + 1) + j;
  27905. indices[indiceIndex++] = i * (stacks + 1) + j + 1;
  27906. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j + 1;
  27907. }
  27908. }
  27909. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  27910. }
  27911. static createQuad(long = 1, width = 1) {
  27912. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  27913. var halfLong = long / 2;
  27914. var halfWidth = width / 2;
  27915. 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]);
  27916. var indices = new Uint16Array([0, 1, 2, 3, 2, 1]);
  27917. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  27918. }
  27919. static createSphere(radius = 0.5, stacks = 32, slices = 32) {
  27920. var vertexCount = (stacks + 1) * (slices + 1);
  27921. var indexCount = (3 * stacks * (slices + 1)) * 2;
  27922. var indices = new Uint16Array(indexCount);
  27923. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  27924. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  27925. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  27926. var stackAngle = Math.PI / stacks;
  27927. var sliceAngle = (Math.PI * 2.0) / slices;
  27928. var vertexIndex = 0;
  27929. vertexCount = 0;
  27930. indexCount = 0;
  27931. for (var stack = 0; stack < (stacks + 1); stack++) {
  27932. var r = Math.sin(stack * stackAngle);
  27933. var y = Math.cos(stack * stackAngle);
  27934. for (var slice = 0; slice < (slices + 1); slice++) {
  27935. var x = r * Math.sin(slice * sliceAngle + Math.PI * 1 / 2);
  27936. var z = r * Math.cos(slice * sliceAngle + Math.PI * 1 / 2);
  27937. vertices[vertexCount + 0] = x * radius;
  27938. vertices[vertexCount + 1] = y * radius;
  27939. vertices[vertexCount + 2] = z * radius;
  27940. vertices[vertexCount + 3] = x;
  27941. vertices[vertexCount + 4] = y;
  27942. vertices[vertexCount + 5] = z;
  27943. vertices[vertexCount + 6] = slice / slices;
  27944. vertices[vertexCount + 7] = stack / stacks;
  27945. vertexCount += vertexFloatStride;
  27946. if (stack != (stacks - 1)) {
  27947. indices[indexCount++] = vertexIndex + (slices + 1);
  27948. indices[indexCount++] = vertexIndex;
  27949. indices[indexCount++] = vertexIndex + 1;
  27950. indices[indexCount++] = vertexIndex + (slices);
  27951. indices[indexCount++] = vertexIndex;
  27952. indices[indexCount++] = vertexIndex + (slices + 1);
  27953. vertexIndex++;
  27954. }
  27955. }
  27956. }
  27957. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  27958. }
  27959. }
  27960. class TextureCube extends Laya.BaseTexture {
  27961. constructor(size, format = Laya.TextureFormat.R8G8B8, mipmap = false) {
  27962. super(format, mipmap);
  27963. this._glTextureType = Laya.LayaGL.instance.TEXTURE_CUBE_MAP;
  27964. this._width = size;
  27965. this._height = size;
  27966. var gl = Laya.LayaGL.instance;
  27967. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  27968. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  27969. this._setFilterMode(this._filterMode);
  27970. this._setAnisotropy(this._anisoLevel);
  27971. if (this._mipmap) {
  27972. this._mipmapCount = Math.ceil(Math.log2(size));
  27973. for (var i = 0; i < this._mipmapCount; i++)
  27974. this._setPixels([], i, Math.max(size >> i, 1), Math.max(size >> i, 1));
  27975. this._setGPUMemory(size * size * 4 * (1 + 1 / 3) * 6);
  27976. }
  27977. else {
  27978. this._mipmapCount = 1;
  27979. this._setGPUMemory(size * size * 4 * 6);
  27980. }
  27981. }
  27982. static __init__() {
  27983. var pixels = new Uint8Array(3);
  27984. pixels[0] = 128;
  27985. pixels[1] = 128;
  27986. pixels[2] = 128;
  27987. TextureCube.grayTexture = new TextureCube(1, Laya.TextureFormat.R8G8B8, false);
  27988. TextureCube.grayTexture.setSixSidePixels([pixels, pixels, pixels, pixels, pixels, pixels]);
  27989. TextureCube.grayTexture.lock = true;
  27990. }
  27991. static _parse(data, propertyParams = null, constructParams = null) {
  27992. var texture = constructParams ? new TextureCube(0, constructParams[0], constructParams[1]) : new TextureCube(0);
  27993. texture.setSixSideImageSources(data);
  27994. return texture;
  27995. }
  27996. static load(url, complete) {
  27997. Laya.ILaya.loader.create(url, complete, null, TextureCube.TEXTURECUBE);
  27998. }
  27999. get defaulteTexture() {
  28000. return TextureCube.grayTexture;
  28001. }
  28002. _setPixels(pixels, miplevel, width, height) {
  28003. var gl = Laya.LayaGL.instance;
  28004. var glFormat = this._getGLFormat();
  28005. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  28006. if (this.format === Laya.TextureFormat.R8G8B8) {
  28007. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  28008. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[0]);
  28009. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[1]);
  28010. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[2]);
  28011. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[3]);
  28012. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[4]);
  28013. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[5]);
  28014. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
  28015. }
  28016. else {
  28017. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[0]);
  28018. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[1]);
  28019. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[2]);
  28020. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[3]);
  28021. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[4]);
  28022. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[5]);
  28023. }
  28024. }
  28025. setSixSideImageSources(source, premultiplyAlpha = false) {
  28026. var width;
  28027. var height;
  28028. for (var i = 0; i < 6; i++) {
  28029. var img = source[i];
  28030. if (!img) {
  28031. console.log("TextureCube: image Source can't be null.");
  28032. return;
  28033. }
  28034. var nextWidth = img.width;
  28035. var nextHeight = img.height;
  28036. if (i > 0) {
  28037. if (width !== nextWidth) {
  28038. console.log("TextureCube: each side image's width and height must same.");
  28039. return;
  28040. }
  28041. }
  28042. width = nextWidth;
  28043. height = nextHeight;
  28044. if (width !== height) {
  28045. console.log("TextureCube: each side image's width and height must same.");
  28046. return;
  28047. }
  28048. }
  28049. this._width = width;
  28050. this._height = height;
  28051. var gl = Laya.LayaGL.instance;
  28052. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  28053. var glFormat = this._getGLFormat();
  28054. if (!Laya.Render.isConchApp) {
  28055. (premultiplyAlpha) && (gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true));
  28056. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[0]);
  28057. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[1]);
  28058. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[2]);
  28059. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[3]);
  28060. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[4]);
  28061. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[5]);
  28062. (premultiplyAlpha) && (gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false));
  28063. }
  28064. else {
  28065. if (premultiplyAlpha == true) {
  28066. for (var j = 0; j < 6; j++)
  28067. source[j].setPremultiplyAlpha(premultiplyAlpha);
  28068. }
  28069. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[0]);
  28070. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[1]);
  28071. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[2]);
  28072. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[3]);
  28073. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[4]);
  28074. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[5]);
  28075. }
  28076. if (this._mipmap && this._isPot(width) && this._isPot(height)) {
  28077. gl.generateMipmap(this._glTextureType);
  28078. this._setGPUMemory(width * height * 4 * (1 + 1 / 3) * 6);
  28079. }
  28080. else {
  28081. this._setGPUMemory(width * height * 4 * 6);
  28082. }
  28083. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  28084. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  28085. this._setFilterMode(this._filterMode);
  28086. this._readyed = true;
  28087. this._activeResource();
  28088. }
  28089. setSixSidePixels(pixels, miplevel = 0) {
  28090. if (!pixels)
  28091. throw new Error("TextureCube:pixels can't be null.");
  28092. var width = Math.max(this._width >> miplevel, 1);
  28093. var height = Math.max(this._height >> miplevel, 1);
  28094. var pixelsCount = width * height * this._getFormatByteCount();
  28095. if (pixels[0].length < pixelsCount)
  28096. throw "TextureCube:pixels length should at least " + pixelsCount + ".";
  28097. this._setPixels(pixels, miplevel, width, height);
  28098. if (miplevel === 0) {
  28099. var gl = Laya.LayaGL.instance;
  28100. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  28101. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  28102. }
  28103. this._readyed = true;
  28104. this._activeResource();
  28105. }
  28106. _recoverResource() {
  28107. }
  28108. }
  28109. TextureCube.TEXTURECUBE = "TEXTURECUBE";
  28110. var BlitScreenPS = "#ifdef FSHIGHPRECISION\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";
  28111. var BlitScreenVS = "#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}";
  28112. var EffectPS = "#ifdef HIGHPRECISION\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";
  28113. var EffectVS = "#include \"Lighting.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\nvoid main()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\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}";
  28114. var extendTerrainPS = "#ifdef HIGHPRECISION\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\r\n#ifdef DIRECTIONLIGHT\r\n\tuniform DirectionLight u_DirectionLight;\r\n#endif\r\n\r\n#ifdef POINTLIGHT\r\n\tuniform PointLight u_PointLight;\r\n#endif\r\n\r\n#ifdef SPOTLIGHT\r\n\tuniform SpotLight u_SpotLight;\r\n#endif\r\n\r\n#include \"ShadowHelper.glsl\"\r\n#ifdef RECEIVESHADOW\r\n\t#if defined(SHADOWMAP_PSSM2)||defined(SHADOWMAP_PSSM3)\r\n\tuniform mat4 u_lightShadowVP[4];\r\n\t#endif\r\n\t#ifdef SHADOWMAP_PSSM1 \r\n\tvarying vec4 v_lightMVPPos;\r\n\t#endif\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#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n vec3 normal = v_Normal;\r\n\tvec3 dif, spe;\r\n#endif\r\n\r\nvec3 diffuse = vec3(0.0);\r\nvec3 specular= vec3(0.0);\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(FOG)\r\n\tvec3 toEye;\r\n\t#ifdef FOG\r\n\t\ttoEye=u_CameraPos-v_PositionWorld;\r\n\t\tfloat toEyeLength=length(toEye);\r\n\t\ttoEye/=toEyeLength;\r\n\t#else\r\n\t\ttoEye=normalize(u_CameraPos-v_PositionWorld);\r\n\t#endif\r\n#endif\r\n\r\n#ifdef DIRECTIONLIGHT\r\n\tLayaAirBlinnPhongDiectionLight(vec3(0.0), 1.0, normal, vec3(1.0), toEye,u_DirectionLight, dif, spe);\r\n\tdiffuse+=dif;\r\n\tspecular+=spe;\r\n#endif\r\n \r\n#ifdef POINTLIGHT\r\n\tLayaAirBlinnPhongPointLight(v_PositionWorld, vec3(0.0), 1.0, normal, vec3(1.0), toEye, u_PointLight, dif, spe);\r\n\tdiffuse+=dif;\r\n\tspecular+=spe;\r\n#endif\r\n\r\n#ifdef SPOTLIGHT\r\n\tLayaAirBlinnPhongSpotLight(v_PositionWorld, vec3(0.0), 1.0, normal, vec3(1.0), toEye, u_SpotLight, dif, spe);\r\n\tdiffuse+=dif;\r\n\tspecular+=spe;\r\n#endif\r\n\r\nvec3 globalDiffuse = u_AmbientColor;\r\n#ifdef LIGHTMAP\r\n\tglobalDiffuse += DecodeLightmap(texture2D(u_LightMap, v_LightMapUV));\r\n#endif\r\n\r\n#ifdef RECEIVESHADOW\r\n\tfloat shadowValue = 1.0;\r\n\t#ifdef SHADOWMAP_PSSM3\r\n\t\tshadowValue = getShadowPSSM3( u_shadowMap1,u_shadowMap2,u_shadowMap3,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t#endif\r\n\t#ifdef SHADOWMAP_PSSM2\r\n\t\tshadowValue = getShadowPSSM2( u_shadowMap1,u_shadowMap2,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t#endif \r\n\t#ifdef SHADOWMAP_PSSM1\r\n\t\tshadowValue = getShadowPSSM1( u_shadowMap1,v_lightMVPPos,u_shadowPSSMDistance,u_shadowPCFoffset,v_posViewZ,0.001);\r\n\t#endif\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#ifdef RECEIVESHADOW\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";
  28115. 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(RECEIVESHADOW)&&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#ifdef RECEIVESHADOW\r\n\tvarying float v_posViewZ;\r\n\t#ifdef SHADOWMAP_PSSM1 \r\n\t\tvarying vec4 v_lightMVPPos;\r\n\t\tuniform mat4 u_lightShadowVP[4];\r\n\t#endif\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(RECEIVESHADOW)&&defined(SHADOWMAP_PSSM1))\r\n\t\tv_PositionWorld=(u_WorldMat*a_Position).xyz;\r\n\t#endif\r\n\r\n\t#ifdef RECEIVESHADOW\r\n\t\tv_posViewZ = gl_Position.w;\r\n\t\t#ifdef SHADOWMAP_PSSM1\r\n\t\t\tv_lightMVPPos = u_lightShadowVP[0] * vec4(v_PositionWorld,1.0);\r\n\t\t#endif\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  28116. var LightingGLSL = "struct 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\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\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 if (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\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\r\n\t// Build orthonormal basis.\r\n\tvec3 N = normalize(unitNormal);\r\n\tvec3 T = normalize(tangent);\r\n\tvec3 B = normalize(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 = TBN*normalT;\r\n\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\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\nmat3 inverse(mat3 m) {\r\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\r\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\r\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\r\n\r\n float b01 = a22 * a11 - a12 * a21;\r\n float b11 = -a22 * a10 + a12 * a20;\r\n float b21 = a21 * a10 - a11 * a20;\r\n\r\n float det = a00 * b01 + a01 * b11 + a02 * b21;\r\n\r\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\r\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\r\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\r\n}\r\n\r\n";
  28117. var linePS = "#ifdef HIGHPRECISION\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";
  28118. var lineVS = "#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}";
  28119. var MeshBlinnPhongPS = "#ifdef HIGHPRECISION\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\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#endif\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\tvarying vec3 v_Normal;\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\t#ifdef NORMALMAP \r\n\t\tuniform sampler2D u_NormalTexture;\r\n\t\tvarying vec3 v_Tangent;\r\n\t\tvarying vec3 v_Binormal;\r\n\t#endif\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\nuniform vec3 u_AmbientColor;\r\n\r\n#if defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\n#include \"ShadowHelper.glsl\"\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n\t#if defined(SHADOWMAP_PSSM2)||defined(SHADOWMAP_PSSM3)\r\n\t\tuniform mat4 u_lightShadowVP[4];\r\n\t#endif\r\n\t#ifdef SHADOWMAP_PSSM1 \r\n\t\tvarying vec4 v_lightMVPPos;\r\n\t#endif\r\n#endif\r\n\r\nvoid main_castShadow()\r\n{\r\n\t//gl_FragColor=vec4(v_posViewZ,0.0,0.0,1.0);\r\n\tgl_FragColor=packDepth(v_posViewZ);\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tfloat alpha = texture2D(u_DiffuseTexture,v_Texcoord0).w;\r\n\t\tif( alpha < u_AlphaTestValue )\r\n\t\t{\r\n\t\t\tdiscard;\r\n\t\t}\r\n\t#endif\r\n}\r\nvoid main_normal()\r\n{\r\n\tvec3 globalDiffuse=u_AmbientColor;\r\n\t#ifdef LIGHTMAP\t\r\n\t\tglobalDiffuse += DecodeLightmap(texture2D(u_LightMap, v_LightMapUV));\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tvec3 normal;\r\n\t\t#if (defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&defined(NORMALMAP)\r\n\t\t\tvec3 normalMapSample = texture2D(u_NormalTexture, v_Texcoord0).rgb;\r\n\t\t\tnormal = normalize(NormalSampleToWorldSpace(normalMapSample, v_Normal, v_Tangent,v_Binormal));\r\n\t\t#else\r\n\t\t\tnormal = normalize(v_Normal);\r\n\t\t#endif\r\n\t\tvec3 viewDir= normalize(v_ViewDir);\r\n\t#endif\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#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\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\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(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\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\t#ifdef RECEIVESHADOW\r\n\t\tfloat shadowValue = 1.0;\r\n\t\t#ifdef SHADOWMAP_PSSM3\r\n\t\t\tshadowValue = getShadowPSSM3(u_shadowMap1,u_shadowMap2,u_shadowMap3,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t\t#ifdef SHADOWMAP_PSSM2\r\n\t\t\tshadowValue = getShadowPSSM2(u_shadowMap1,u_shadowMap2,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif \r\n\t\t#ifdef SHADOWMAP_PSSM1\r\n\t\t\tshadowValue = getShadowPSSM1(u_shadowMap1,v_lightMVPPos,u_shadowPSSMDistance,u_shadowPCFoffset,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t\tgl_FragColor =vec4(mainColor.rgb*(globalDiffuse + diffuse*shadowValue),mainColor.a);\r\n\t#else\r\n\t\tgl_FragColor =vec4(mainColor.rgb*(globalDiffuse + diffuse),mainColor.a);\r\n\t#endif\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t#ifdef RECEIVESHADOW\r\n\t\t\tgl_FragColor.rgb+=specular*shadowValue;\r\n\t\t#else\r\n\t\t\tgl_FragColor.rgb+=specular;\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\tgl_FragColor.rgb=mix(gl_FragColor.rgb,u_FogColor,lerpFact);\r\n\t#endif\r\n}\r\n\r\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\t\t\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif \r\n}\r\n\r\n";
  28120. var MeshBlinnPhongVS = "#include \"Lighting.glsl\";\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\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\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\tattribute vec3 a_Normal;\r\n\tvarying vec3 v_Normal; \r\n\tuniform vec3 u_CameraPos;\r\n\tvarying vec3 v_ViewDir; \r\n#endif\r\n\r\n#if (defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&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#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)\r\n\t#ifdef GPU_INSTANCE\r\n\t\tattribute mat4 a_WorldMat;\r\n\t#else\r\n\t\tuniform mat4 u_WorldMat;\r\n\t#endif\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n #ifdef SHADOWMAP_PSSM1 \r\n varying vec4 v_lightMVPPos;\r\n uniform mat4 u_lightShadowVP[4];\r\n #endif\r\n#endif\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\nvoid main_castShadow()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\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//TODO没考虑UV动画呢\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tv_Texcoord0=a_Texcoord0;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n\tv_posViewZ = gl_Position.z;\r\n}\r\n\r\nvoid main_normal()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\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#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)\r\n\t\tmat4 worldMat;\r\n\t\t#ifdef GPU_INSTANCE\r\n\t\t\tworldMat = a_WorldMat;\r\n\t\t#else\r\n\t\t\tworldMat = u_WorldMat;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tmat3 worldInvMat;\r\n\t\t#ifdef BONE\r\n\t\t\tworldInvMat=inverse(mat3(worldMat*skinTransform));\r\n\t\t#else\r\n\t\t\tworldInvMat=inverse(mat3(worldMat));\r\n\t\t#endif \r\n\t\tv_Normal=a_Normal*worldInvMat;\r\n\t\t#if (defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&defined(NORMALMAP)\r\n\t\t\tv_Tangent=a_Tangent0.xyz*worldInvMat;\r\n\t\t\tv_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)\r\n\t\tv_PositionWorld=(worldMat*position).xyz;\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tv_ViewDir=u_CameraPos-v_PositionWorld;\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 SCALEOFFSETLIGHTINGMAPUV\r\n\t\t\t#ifdef UV1\r\n\t\t\t\tv_LightMapUV=vec2(a_Texcoord1.x,1.0-a_Texcoord1.y)*u_LightmapScaleOffset.xy+u_LightmapScaleOffset.zw;\r\n\t\t\t#else\r\n\t\t\t\tv_LightMapUV=vec2(a_Texcoord0.x,1.0-a_Texcoord0.y)*u_LightmapScaleOffset.xy+u_LightmapScaleOffset.zw;\r\n\t\t\t#endif \r\n\t\t\tv_LightMapUV.y=1.0-v_LightMapUV.y;\r\n\t\t#else\r\n\t\t\t#ifdef UV1\r\n\t\t\t\tv_LightMapUV=a_Texcoord1;\r\n\t\t\t#else\r\n\t\t\t\tv_LightMapUV=a_Texcoord0;\r\n\t\t\t#endif \r\n\t\t#endif \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#ifdef RECEIVESHADOW\r\n\t\tv_posViewZ = gl_Position.w;\r\n\t\t#ifdef SHADOWMAP_PSSM1 \r\n\t\t\tv_lightMVPPos = u_lightShadowVP[0] * vec4(v_PositionWorld,1.0);\r\n\t\t#endif\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n\r\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif\r\n}";
  28121. var ParticleShuriKenPS = "#ifdef HIGHPRECISION\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}";
  28122. var ParticleShuriKenVS = "#include \"Lighting.glsl\";\r\n\r\n#ifdef HIGHPRECISION\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\tvec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\r\n\t\tvec3 velocity;\r\n\t\t#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n\t\t\tif(u_VOLSpaceType==0)\r\n\t\t\tvelocity=rotationByQuaternions(u_SizeScale*(startVelocity+lifeVelocity),worldRotation)+gravityVelocity;\r\n\t\t\telse\r\n\t\t\tvelocity=rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+lifeVelocity+gravityVelocity;\r\n\t\t#else\r\n\t\t\tvelocity= rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+gravityVelocity;\r\n\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";
  28123. var BRDFGLSL = "struct LayaGI\r\n{\r\n\tvec3 diffuse;\r\n\tvec3 specular;\r\n};\r\n\r\nvec4 LayaAirBRDF(in vec3 diffuseColor, in vec3 specularColor, in float oneMinusReflectivity, in float smoothness, in vec3 normal, in vec3 viewDir, in vec3 lightDir, in vec3 lightColor, in LayaGI gi)\r\n{\r\n\tfloat perceptualRoughness = SmoothnessToPerceptualRoughness(smoothness);\r\n\tvec3 halfDir = SafeNormalize(viewDir - lightDir);\r\n\t\r\n\tfloat nv = abs(dot(normal, viewDir));\r\n\t\r\n\tfloat nl = clamp(dot(normal, -lightDir), 0.0, 1.0);\r\n\tfloat nh = clamp(dot(normal, halfDir), 0.0, 1.0);\r\n\tfloat lv = clamp(dot(lightDir, viewDir), 0.0, 1.0);\r\n\tfloat lh = clamp(dot(lightDir, -halfDir), 0.0, 1.0);\r\n\t\r\n\tfloat diffuseTerm = DisneyDiffuse(nv, nl, lh, perceptualRoughness) * nl;\r\n\t\r\n\tfloat roughness = PerceptualRoughnessToRoughness(perceptualRoughness);\r\n\t\r\n\t//#if UNITY_BRDF_GGX\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.014);\r\n\tfloat V = SmithJointGGXVisibilityTerm(nl, nv, roughness);\r\n\tfloat D = GGXTerm(nh, roughness);\r\n\t\r\n\tfloat specularTerm = V * D * PI;\r\n\t\r\n\tspecularTerm = sqrt(max(0.0001, specularTerm));\r\n\tspecularTerm = max(0.0, specularTerm * nl);\r\n\t\r\n\tfloat surfaceReduction = 1.0 - 0.28 * roughness * perceptualRoughness;\r\n\tfloat grazingTerm = clamp(smoothness + (1.0 - oneMinusReflectivity), 0.0, 1.0);\r\n\t\r\n\tvec4 color;\r\n\tcolor.rgb = diffuseColor * (gi.diffuse+lightColor * diffuseTerm) \r\n\t\t\t + specularTerm * lightColor * FresnelTerm (specularColor, lh);\r\n\t\t\t //+ surfaceReduction * gi.specular * FresnelLerp(specularColor, vec3(grazingTerm), nv);\r\n\t\r\n\treturn color;\r\n}\r\nvec4 LayaAirStandardReflect(in vec4 albedoColor,in float metallic,in float smoothness,in LayaGI gi)\r\n{\r\n\tvec3 diffuseColor;\r\n\tvec3 specularColor;\r\n\tfloat alpha;\r\n\tfloat oneMinusReflectivity;\r\n\tdiffuseColor = DiffuseAndSpecularFromMetallic (albedoColor.rgb, metallic, specularColor, oneMinusReflectivity);\r\n\tdiffuseColor = LayaPreMultiplyAlpha(diffuseColor, albedoColor.a, oneMinusReflectivity, alpha);\r\n\tfloat perceptualRoughness = SmoothnessToPerceptualRoughness(smoothness);\r\n\tfloat roughness = PerceptualRoughnessToRoughness(perceptualRoughness);\r\n\tfloat surfaceReduction = 1.0 - 0.28 * roughness * perceptualRoughness;\r\n\tvec4 color;\r\n\tcolor.rgb = surfaceReduction * gi.specular;\r\n\tcolor.a = alpha;\r\n\treturn color;\r\n\r\n}\r\n\r\nvec4 LayaAirSpecularReflect(in vec4 albedoColor,in vec3 specularColor,in float smoothness,in LayaGI gi)\r\n{\r\n\tfloat oneMinusReflectivity;\r\n\tvec3 diffuseColor;\r\n\tfloat alpha;\r\n\t\r\n\tdiffuseColor = EnergyConservationBetweenDiffuseAndSpecular (albedoColor.rgb, specularColor, oneMinusReflectivity);\r\n\t\r\n\tdiffuseColor = LayaPreMultiplyAlpha(diffuseColor, albedoColor.a, oneMinusReflectivity, alpha);\r\n\r\n\tfloat perceptualRoughness = SmoothnessToPerceptualRoughness(smoothness);\r\n\tfloat roughness = PerceptualRoughnessToRoughness(perceptualRoughness);\r\n\tfloat surfaceReduction = 1.0 - 0.28 * roughness * perceptualRoughness;\r\n\tvec4 color;\r\n\tcolor.rgb = surfaceReduction * gi.specular;\r\n\tcolor.a = alpha;\r\n\treturn color;\r\n}";
  28124. var PBRSpecularLightingGLSL = "#include \"PBRUtils.glsl\"\r\n#include \"BRDF.glsl\"\r\n\r\nvec4 PBRSpecularLight(in vec4 albedoColor, in vec3 specularColor, in float smoothness, in vec3 normal, in vec3 viewDir, in vec3 lightDir, in vec3 lightColor, in LayaGI gi)\r\n{\r\n\tfloat oneMinusReflectivity;\r\n\tvec3 diffuseColor;\r\n\tfloat alpha;\r\n\t\r\n\tdiffuseColor = EnergyConservationBetweenDiffuseAndSpecular (albedoColor.rgb, specularColor, oneMinusReflectivity);\r\n\t\r\n\tdiffuseColor = LayaPreMultiplyAlpha(diffuseColor, albedoColor.a, oneMinusReflectivity, alpha);\r\n\t\r\n\tvec4 color = LayaAirBRDF(diffuseColor, specularColor, oneMinusReflectivity, smoothness, normal, viewDir, lightDir, lightColor, gi);\r\n\tcolor.a = alpha;\r\n\treturn color;\r\n}\r\n\r\nvec4 PBRSpecularDiectionLight (in vec4 albedoColor, in vec3 specularColor, in float smoothness, in vec3 normal, in vec3 viewDir, in DirectionLight light, in LayaGI gi)\r\n{\r\n\tvec3 lightVec = normalize(light.direction);\r\n\treturn PBRSpecularLight(albedoColor, specularColor, smoothness, normal, viewDir, lightVec, light.color, gi);\r\n}\r\n#ifdef POINTLIGHT\r\nvec4 PBRSpecularPointLight (in vec4 albedoColor, in vec3 specularColor, in float smoothness, in vec3 normal, in vec3 viewDir, in PointLight light, in vec3 pos, in LayaGI gi)\r\n{\r\n\tvec3 lightVec = pos-light.position;\r\n\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range);\r\n\treturn PBRSpecularLight(albedoColor, specularColor, smoothness, normal, viewDir, lightVec, light.color, gi) * attenuate;\r\n}\r\n#endif\r\nvec4 PBRSpecularSpotLight (in vec4 albedoColor, in vec3 specularColor, in float smoothness, in vec3 normal, in vec3 viewDir, in SpotLight light, in vec3 pos, in LayaGI gi)\r\n{\r\n\tvec3 lightVec = pos - light.position;\r\n\tvec3 normalLightVec = normalize(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\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range) * dl;\r\n\treturn PBRSpecularLight(albedoColor, specularColor, smoothness, normal, viewDir, lightVec, light.color, gi) * attenuate;\r\n}\r\n\r\n//vec4 PBRStandardSpotLight1 (in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in SpotLight light, in vec3 pos, in LayaGI gi)\r\n//{\r\n//\tvec4 lightCoord = u_SpotLightMatrix * vec4(pos, 1.0);\r\n//\t\r\n//\tfloat distance = dot(lightCoord, lightCoord);\r\n//\tfloat attenuate = (lightCoord.z < 0.0) ? texture2D(u_RangeTexture, vec2(distance)).w : 0.0;\r\n//\t//float attenuate = (lightCoord.z < 0.0) ? texture2D(u_AngleTexture, vec2(lightCoord.x / lightCoord.w + 0.5, lightCoord.y / lightCoord.w + 0.5)).r * texture2D(u_RangeTexture, vec2(distance)).w : 0.0;\r\n//\t//vec2 _uv = vec2(pos.x * 180.0/(2.0 * pos.z) + 0.5, pos.y * 180.0/(2.0 * pos.z) + 0.5);\r\n//\tvec3 lightVec = normalize(pos - light.cosition);\r\n//\treturn PBRStandardLight(albedoColor, metallic, smoothness, normal, viewDir, lightVec, light.color, gi) * attenuate;\r\n//}\r\n\r\nvec4 SpecularGloss(float albedoTextureAlpha, in vec2 uv0)\r\n{\r\n vec4 sg;\r\n\t\r\n\t#ifdef SPECULARTEXTURE\r\n\t\tvec4 specularTextureColor = texture2D(u_SpecularTexture, uv0);\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tsg.rgb = specularTextureColor.rgb;\r\n\t\t\tsg.a = albedoTextureAlpha;\r\n\t\t#else\r\n\t\t\tsg = specularTextureColor;\r\n\t\t#endif\r\n\t\tsg.a *= u_smoothnessScale;\r\n\t#else\r\n\t\tsg.rgb = u_SpecularColor.rgb;\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tsg.a = albedoTextureAlpha * u_smoothnessScale;\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\r\n return sg;\r\n}\r\n\r\n";
  28125. var PBRStandardLightingGLSL = "#include \"PBRUtils.glsl\"\r\n#include \"BRDF.glsl\"\r\n\r\nvec4 PBRStandardLight(in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in vec3 lightDir, in vec3 lightColor, in LayaGI gi)\r\n{\r\n\tfloat oneMinusReflectivity;\r\n\tvec3 diffuseColor;\r\n\tvec3 specularColor;\r\n\tfloat alpha;\r\n\t\r\n\tdiffuseColor = DiffuseAndSpecularFromMetallic (albedoColor.rgb, metallic, specularColor, oneMinusReflectivity);\r\n\t\r\n\tdiffuseColor = LayaPreMultiplyAlpha(diffuseColor, albedoColor.a, oneMinusReflectivity, alpha);\r\n\t\r\n\tvec4 color = LayaAirBRDF(diffuseColor, specularColor, oneMinusReflectivity, smoothness, normal, viewDir, lightDir, lightColor, gi);\r\n\tcolor.a = alpha;\r\n\treturn color;\r\n}\r\n\r\nvec4 PBRStandardDiectionLight (in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in DirectionLight light, in LayaGI gi)\r\n{\r\n\tvec3 lightVec = normalize(light.direction);\r\n\treturn PBRStandardLight(albedoColor, metallic, smoothness, normal, viewDir, lightVec, light.color, gi);\r\n}\r\n#ifdef POINTLIGHT\r\nvec4 PBRStandardPointLight (in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in PointLight light, in vec3 pos, in LayaGI gi)\r\n{\r\n\tvec3 lightVec = pos-light.position;\r\n\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range);\r\n\treturn PBRStandardLight(albedoColor, metallic, smoothness, normal, viewDir, lightVec, light.color, gi) * attenuate;\r\n}\r\n#endif\r\nvec4 PBRStandardSpotLight (in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in SpotLight light, in vec3 pos, in LayaGI gi)\r\n{\r\n\tvec3 lightVec = pos - light.position;\r\n\tvec3 normalLightVec = normalize(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\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range) * dl;\r\n\treturn PBRStandardLight(albedoColor, metallic, smoothness, normal, viewDir, lightVec, light.color, gi) * attenuate;\r\n\t\r\n}\r\n\r\n//vec4 PBRStandardSpotLight1 (in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in SpotLight light, in vec3 pos, in LayaGI gi)\r\n//{\r\n//\tvec4 lightCoord = u_SpotLightMatrix * vec4(pos, 1.0);\r\n//\t\r\n//\tfloat distance = dot(lightCoord, lightCoord);\r\n//\tfloat attenuate = (lightCoord.z < 0.0) ? texture2D(u_RangeTexture, vec2(distance)).w : 0.0;\r\n//\t//float attenuate = (lightCoord.z < 0.0) ? texture2D(u_AngleTexture, vec2(lightCoord.x / lightCoord.w + 0.5, lightCoord.y / lightCoord.w + 0.5)).r * texture2D(u_RangeTexture, vec2(distance)).w : 0.0;\r\n//\t//vec2 _uv = vec2(pos.x * 180.0/(2.0 * pos.z) + 0.5, pos.y * 180.0/(2.0 * pos.z) + 0.5);\r\n//\tvec3 lightVec = normalize(pos - light.position);\r\n//\treturn PBRStandardLight(albedoColor, metallic, smoothness, normal, viewDir, lightVec, light.color, gi) * attenuate;\r\n//}\r\n\r\nvec2 MetallicGloss(in float albedoTextureAlpha, in vec2 uv0)\r\n{\r\n\tvec2 mg;\r\n\t\r\n\t#ifdef METALLICGLOSSTEXTURE\r\n\t\tvec4 metallicGlossTextureColor = texture2D(u_MetallicGlossTexture, uv0);\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tmg.r = metallicGlossTextureColor.r;\r\n\t\t\tmg.g = albedoTextureAlpha;\r\n\t\t#else\r\n\t\t mg = metallicGlossTextureColor.ra;\r\n\t\t#endif\r\n\t\tmg.g *= u_smoothnessScale;\r\n\t#else\r\n\t\tmg.r = u_metallic;\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tmg.g = albedoTextureAlpha * u_smoothnessScale;\r\n\t\t#else\r\n\t\t\tmg.g = u_smoothness;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\treturn mg;\r\n}\r\n\r\n";
  28126. var PBRUtilsGLSL = "\r\nvec3 UnpackScaleNormal(in vec2 uv0)\r\n{\r\n\t#ifdef NORMALTEXTURE\r\n\t\tvec3 normalT;\r\n\t\tvec4 normalMapSample = texture2D(u_NormalTexture, uv0);\r\n\t\tnormalT.x = 2.0 * normalMapSample.x - 1.0;\r\n\t\tnormalT.y = 1.0 - 2.0 * normalMapSample.y;\r\n\t\tnormalT.xy *= u_normalScale;\r\n\t\tnormalT.z = sqrt(1.0 - clamp(dot(normalT.xy, normalT.xy), 0.0, 1.0));\r\n\t\t\r\n\t\tvec3 T = normalize(v_Tangent);\r\n\t\tvec3 B = normalize(v_Binormal);\r\n\t\tvec3 N = normalize(v_Normal);\r\n\t\tmat3 TBN = mat3(T, B, N);\r\n\t\t\r\n\t\tvec3 bumpedNormal = TBN * normalize(normalT);\r\n\t\treturn bumpedNormal;\r\n\t#else\r\n\t\treturn normalize(v_Normal);\r\n\t#endif\r\n}\r\n\r\nvec4 DielectricSpecularColor = vec4(0.220916301, 0.220916301, 0.220916301, 1.0 - 0.220916301);\r\n\r\nfloat PI = 3.14159265359;\r\n\r\nvec3 FresnelTerm (in vec3 F0, in float cosA)\r\n{\r\n\treturn F0 + (vec3(1.0) - F0) * pow(1.0 - cosA, 5.0);\r\n}\r\n\r\nvec3 FresnelLerp (in vec3 F0, in vec3 F90, float cosA)\r\n{\r\n float t = pow(1.0 - cosA, 5.0);\r\n return mix(F0, F90, t);\r\n}\r\n\r\nfloat PerceptualRoughnessToRoughness(in float perceptualRoughness)\r\n{\r\n\treturn perceptualRoughness * perceptualRoughness;\r\n}\r\n\r\nfloat PerceptualRoughnessToSpecularPower(in float perceptualRoughness)\r\n{\r\n\tfloat m = PerceptualRoughnessToRoughness(perceptualRoughness);\r\n\tfloat sq = max(0.0001, m * m);\r\n\tfloat n = (2.0 / sq) - 2.0;\r\n\tn = max(n, 0.0001);\r\n\treturn n;\r\n}\r\n\r\nfloat RoughnessToPerceptualRoughness(in float roughness)\r\n{\r\n\treturn sqrt(roughness);\r\n}\r\n\r\nfloat SmoothnessToRoughness(in float smoothness)\r\n{\r\n\treturn (1.0 - smoothness) * (1.0 - smoothness);\r\n}\r\n\r\nfloat SmoothnessToPerceptualRoughness(in float smoothness)\r\n{\r\n\treturn (1.0 - smoothness);\r\n}\r\n\r\nvec3 SafeNormalize(in vec3 inVec)\r\n{\r\n\tfloat dp3 = max(0.001,dot(inVec,inVec));\r\n\treturn inVec * (1.0 / sqrt(dp3));\r\n}\r\n\r\nfloat DisneyDiffuse(in float NdotV, in float NdotL, in float LdotH, in float perceptualRoughness)\r\n{\r\n\tfloat fd90 = 0.5 + 2.0 * LdotH * LdotH * perceptualRoughness;\r\n\tfloat lightScatter\t= (1.0 + (fd90 - 1.0) * pow(1.0 - NdotL,5.0));\r\n\tfloat viewScatter\t= (1.0 + (fd90 - 1.0) * pow(1.0 - NdotV,5.0));\r\n\r\n\treturn lightScatter * viewScatter;\r\n}\r\n\r\nfloat SmithJointGGXVisibilityTerm (float NdotL, float NdotV, float roughness)\r\n{\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\r\n\treturn 0.5 / (lambdaV + lambdaL + 0.00001);\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;\r\n\treturn 0.31830988618 * a2 / (d * d + 0.0000001);\r\n}\r\n\r\nfloat OneMinusReflectivityFromMetallic(in float metallic)\r\n{\r\n\tfloat oneMinusDielectricSpec = DielectricSpecularColor.a;\r\n\treturn oneMinusDielectricSpec - metallic * oneMinusDielectricSpec;\r\n}\r\n\r\nfloat SpecularStrength(vec3 specular)\r\n{\r\n //(SHADER_TARGET < 30)return specular.r; \r\n return max (max (specular.r, specular.g), specular.b);\r\n}\r\n\r\nvec3 DiffuseAndSpecularFromMetallic(in vec3 diffuseColor, in float metallic, out vec3 specularColor, out float oneMinusReflectivity)\r\n{\r\n\tspecularColor = mix(DielectricSpecularColor.rgb, diffuseColor, metallic);\r\n\toneMinusReflectivity = OneMinusReflectivityFromMetallic(metallic);\r\n\treturn diffuseColor * oneMinusReflectivity;\r\n}\r\n\r\nvec3 EnergyConservationBetweenDiffuseAndSpecular(in vec3 diffuseColor, in vec3 specularColor, out float oneMinusReflectivity)\r\n{\r\n\toneMinusReflectivity = 1.0 - SpecularStrength(specularColor);\r\n\treturn diffuseColor * oneMinusReflectivity;\r\n}\r\n\r\nvec4 Occlusion(in vec2 uv0){\r\n\t#ifdef OCCLUSIONTEXTURE\r\n\t\tvec4 occlusionTextureColor = texture2D(u_OcclusionTexture, uv0);\r\n\t\tfloat occ = occlusionTextureColor.g;\r\n\t\tfloat oneMinusT = 1.0 - u_occlusionStrength;\r\n\t\tfloat lerpOneTo = oneMinusT + occ * u_occlusionStrength;\r\n\t\treturn occlusionTextureColor * lerpOneTo;\r\n\t#else\r\n\t\treturn vec4(1.0);\r\n\t#endif\r\n}\r\n\r\nvec2 ParallaxOffset(in vec3 viewDir){\r\n\t#ifdef PARALLAXTEXTURE\r\n\t\tfloat h = texture2D(u_ParallaxTexture, v_Texcoord0).g;\r\n\t\th = h * u_parallaxScale - u_parallaxScale / 2.0;\r\n\t\tvec3 v = viewDir;\r\n\t\tv.z += 0.42;\r\n\t\tvec2 offset = h * (v.xy / v.z);\r\n\t\treturn v_Texcoord0 + offset;\r\n\t#else\r\n\t\treturn v_Texcoord0;\r\n\t#endif\r\n}\r\n\r\nvec3 ReflectCubeMap(in vec3 viewDir, in vec3 normal){\r\n\t#ifdef REFLECTMAP\r\n\t\tvec3 incident = -viewDir;\r\n\t\tvec3 reflectionVector = reflect(incident, normal);\r\n\t\tvec3 reflectionColor = textureCube(u_ReflectTexture, vec3(-reflectionVector.x, reflectionVector.yz)).rgb;\r\n\t\treturn reflectionColor * u_ReflectIntensity;\r\n\t#else\r\n\t\treturn vec3(0.0);\r\n\t#endif\r\n}\r\n\r\n\r\n\r\nvec3 LayaPreMultiplyAlpha(vec3 diffColor, float alpha, float oneMinusReflectivity, out float outModifiedAlpha)\r\n{\r\n\t#ifdef ALPHAPREMULTIPLY\r\n\t\tdiffColor *= alpha;\r\n\t\toutModifiedAlpha = 1.0 - oneMinusReflectivity + alpha * oneMinusReflectivity;\r\n\t#else\r\n\t\toutModifiedAlpha = alpha;\r\n\t#endif\r\n\treturn diffColor;\r\n}\r\n\r\n";
  28127. var PBRSpecularPS = "#ifdef HIGHPRECISION\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec3 v_PositionWorld;\r\n\r\nuniform vec3 u_AmbientColor;\r\nuniform vec4 u_AlbedoColor;\r\nuniform vec4 u_SpecularColor;\r\n\r\n#ifdef ALBEDOTEXTURE\r\n\tuniform sampler2D u_AlbedoTexture;\r\n#endif\r\n#ifdef SPECULARTEXTURE\r\n\tuniform sampler2D u_SpecularTexture;\r\n#endif\r\n#ifdef NORMALTEXTURE\r\n\tuniform sampler2D u_NormalTexture;\r\n\tuniform float u_normalScale;\r\n#endif\r\n#ifdef PARALLAXTEXTURE\r\n\tuniform sampler2D u_ParallaxTexture;\r\n\tuniform float u_parallaxScale;\r\n#endif\r\n#ifdef OCCLUSIONTEXTURE\r\n\tuniform sampler2D u_OcclusionTexture;\r\n\tuniform float u_occlusionStrength;\r\n#endif\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#ifdef REFLECTMAP\r\n\tuniform samplerCube u_ReflectTexture;\r\n\tuniform float u_ReflectIntensity;\r\n#endif\r\n\r\nuniform float u_AlphaTestValue;\r\nuniform float u_metallic;\r\nuniform float u_smoothness;\r\nuniform float u_smoothnessScale;\r\n\r\n\r\n\r\n#include \"Lighting.glsl\";\r\n#include \"PBRSpecularLighting.glsl\"\r\n#include \"ShadowHelper.glsl\"\r\n\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n\t#if defined(SHADOWMAP_PSSM2)||defined(SHADOWMAP_PSSM3)\r\n\t\tuniform mat4 u_lightShadowVP[4];\r\n\t#endif\r\n\t#ifdef SHADOWMAP_PSSM1 \r\n\t\tvarying vec4 v_lightMVPPos;\r\n\t#endif\r\n#endif\r\n\r\n#ifdef LEGACYSINGLELIGHTING\r\n\t#ifdef DIRECTIONLIGHT\r\n\t\tuniform DirectionLight u_DirectionLight;\r\n\t#endif\r\n\t#ifdef POINTLIGHT\r\n\t\tuniform PointLight u_PointLight;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT\r\n\t\tuniform SpotLight u_SpotLight;\r\n\t#endif\r\n#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#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\nvoid main_castShadow()\r\n{\r\n\tgl_FragColor=packDepth(v_posViewZ);\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tfloat alpha = texture2D(u_AlbedoTexture,v_Texcoord0).w;\r\n\t\tif( alpha < u_AlphaTestValue )\r\n\t\t{\r\n\t\t\tdiscard;\r\n\t\t}\r\n\t#endif\r\n}\r\n\r\nvoid main_normal()\r\n{\t\r\n\tvec3 viewDir = normalize(v_ViewDir);\r\n\t\r\n\tvec2 uv0 = ParallaxOffset(viewDir);\r\n\t\r\n\tvec4 sg;\r\n\tvec4 albedoColor;\r\n\t#ifdef ALBEDOTEXTURE\r\n\t\tvec4 albedoTextureColor = texture2D(u_AlbedoTexture, uv0);\r\n\t\talbedoColor = albedoTextureColor * u_AlbedoColor;\r\n\t\tsg = SpecularGloss(albedoTextureColor.a, uv0);\r\n\t#else\r\n\t\talbedoColor = u_AlbedoColor;\r\n\t\tsg = SpecularGloss(1.0, uv0);\r\n\t#endif\r\n\t\r\n\t#ifdef ALPHATEST\r\n\t\tif(albedoColor.a < u_AlphaTestValue)\r\n\t\t\tdiscard;\r\n\t#endif\r\n \r\n\tvec3 normal = UnpackScaleNormal(uv0);\r\n\t\r\n\tLayaGI gi;\r\n\tgi.diffuse = u_AmbientColor * Occlusion(uv0).rgb;\r\n\tgi.specular = ReflectCubeMap(viewDir, normal);\r\n\t\r\n\t//float a = (sg.r+sg.g+sg.b) / 3.0;\r\n \r\n\tvec4 color = vec4(0.0);\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tcolor += PBRSpecularDiectionLight(albedoColor, sg.rgb, sg.a, normal, viewDir, u_DirectionLight, gi);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tcolor.a = 0.0;\r\n\t\t\tcolor += PBRSpecularPointLight(albedoColor, sg.rgb, sg.a, normal, viewDir, u_PointLight, v_PositionWorld, gi);\r\n\t\t#endif\r\n\t\t\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tcolor.a = 0.0;\r\n\t\t\tcolor += PBRSpecularSpotLight(albedoColor, sg.rgb, sg.a, normal, viewDir, u_SpotLight, v_PositionWorld, gi);\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\tcolor.a = 0.0;\r\n\t\t\t\tcolor +=PBRSpecularDiectionLight(albedoColor, sg.rgb, sg.a, normal, viewDir, directionLight, gi);\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\tcolor.a = 0.0;\r\n\t\t\t\t\tcolor +=PBRSpecularPointLight(albedoColor, sg.rgb, sg.a, normal, viewDir, pointLight, v_PositionWorld, gi);\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\tcolor.a = 0.0;\r\n\t\t\t\t\tcolor += PBRSpecularSpotLight(albedoColor, sg.rgb, sg.a, normal, viewDir, spotLight, v_PositionWorld, gi);\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t#ifdef REFLECTMAP\r\n\t \tcolor += LayaAirSpecularReflect(albedoColor,sg.rgb,sg.a,gi);\r\n\t#endif\r\n\r\n\t#ifdef EMISSION\r\n\t\tvec4 emissionColor = u_EmissionColor;\r\n\t\t#ifdef EMISSIONTEXTURE\r\n\t\t\temissionColor *= texture2D(u_EmissionTexture, uv0);\r\n\t\t#endif\r\n\t\tcolor.rgb += emissionColor.rgb;\r\n\t#endif\r\n\t\r\n\t#ifdef RECEIVESHADOW\r\n\t\tfloat shadowValue = 1.0;\r\n\t\t#ifdef SHADOWMAP_PSSM3\r\n\t\t\tshadowValue = getShadowPSSM3( u_shadowMap1,u_shadowMap2,u_shadowMap3,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t\t#ifdef SHADOWMAP_PSSM2\r\n\t\t\tshadowValue = getShadowPSSM2( u_shadowMap1,u_shadowMap2,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif \r\n\t\t#ifdef SHADOWMAP_PSSM1\r\n\t\t\tshadowValue = getShadowPSSM1( u_shadowMap1,v_lightMVPPos,u_shadowPSSMDistance,u_shadowPCFoffset,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t\tgl_FragColor = vec4(color.rgb * shadowValue, color.a);\r\n\t#else\r\n\t\tgl_FragColor = color;\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\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\t\t\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif \r\n}\r\n\r\n";
  28128. var PBRSpecularVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec3 a_Normal;\r\nattribute vec4 a_Tangent0;\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 GPU_INSTANCE\r\n\tattribute mat4 a_WorldMat;\r\n#else\r\n\tuniform mat4 u_WorldMat;\r\n#endif\r\nuniform vec3 u_CameraPos;\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec3 v_PositionWorld;\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n #ifdef SHADOWMAP_PSSM1 \r\n\t varying vec4 v_lightMVPPos;\r\n\t uniform mat4 u_lightShadowVP[4];\r\n #endif\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_castShadow()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\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//TODO没考虑UV动画呢\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tv_Texcoord0 = a_Texcoord0;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n\tv_posViewZ = gl_Position.z;\r\n}\r\n\r\nvoid main_normal()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\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#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)||defined(REFLECTMAP)\r\n\t\tmat4 worldMat;\r\n\t\t#ifdef GPU_INSTANCE\r\n\t\t\tworldMat = a_WorldMat;\r\n\t\t#else\r\n\t\t\tworldMat = u_WorldMat;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(REFLECTMAP)\r\n\t\tmat3 worldInvMat;\r\n\t\t#ifdef BONE\r\n\t\t\tworldInvMat=inverse(mat3(worldMat*skinTransform));\r\n\t\t#else\r\n\t\t\tworldInvMat=inverse(mat3(worldMat));\r\n\t\t#endif \r\n\t\tv_Normal=a_Normal*worldInvMat;\r\n\t\t#if (defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))\r\n\t\t\tv_Tangent=a_Tangent0.xyz*worldInvMat;\r\n\t\t\tv_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)||defined(REFLECTMAP)\r\n\t\tv_PositionWorld=(worldMat*position).xyz;\r\n\t#endif\r\n\t\r\n \r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(REFLECTMAP)\r\n\t\tv_ViewDir=u_CameraPos-v_PositionWorld;\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#ifdef RECEIVESHADOW\r\n\t\tv_posViewZ = gl_Position.w;\r\n\t\t#ifdef SHADOWMAP_PSSM1 \r\n\t\t\tv_lightMVPPos = u_lightShadowVP[0] * vec4(v_PositionWorld,1.0);\r\n\t\t#endif\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n\r\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif\r\n}";
  28129. var PBRStandardPS = "#ifdef HIGHPRECISION\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec3 v_PositionWorld;\r\n\r\nuniform vec3 u_AmbientColor;\r\nuniform vec4 u_AlbedoColor;\r\n\r\n#ifdef ALBEDOTEXTURE\r\n\tuniform sampler2D u_AlbedoTexture;\r\n#endif\r\n#ifdef METALLICGLOSSTEXTURE\r\n\tuniform sampler2D u_MetallicGlossTexture;\r\n#endif\r\n#ifdef NORMALTEXTURE\r\n\tuniform sampler2D u_NormalTexture;\r\n\tuniform float u_normalScale;\r\n#endif\r\n#ifdef PARALLAXTEXTURE\r\n\tuniform sampler2D u_ParallaxTexture;\r\n\tuniform float u_parallaxScale;\r\n#endif\r\n#ifdef OCCLUSIONTEXTURE\r\n\tuniform sampler2D u_OcclusionTexture;\r\n\tuniform float u_occlusionStrength;\r\n#endif\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#ifdef REFLECTMAP\r\n\tuniform samplerCube u_ReflectTexture;\r\n\tuniform float u_ReflectIntensity;\r\n#endif\r\n\r\nuniform float u_AlphaTestValue;\r\nuniform float u_metallic;\r\nuniform float u_smoothness;\r\nuniform float u_smoothnessScale;\r\n\r\n\r\n\r\n\r\n#include \"Lighting.glsl\";\r\n#include \"PBRStandardLighting.glsl\"\r\n#include \"ShadowHelper.glsl\"\r\n\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n\t#if defined(SHADOWMAP_PSSM2)||defined(SHADOWMAP_PSSM3)\r\n\t\tuniform mat4 u_lightShadowVP[4];\r\n\t#endif\r\n\t#ifdef SHADOWMAP_PSSM1 \r\n\t\tvarying vec4 v_lightMVPPos;\r\n\t#endif\r\n#endif\r\n\r\n#ifdef LEGACYSINGLELIGHTING\r\n\t#ifdef DIRECTIONLIGHT\r\n\t\tuniform DirectionLight u_DirectionLight;\r\n\t#endif\r\n\t#ifdef POINTLIGHT\r\n\t\tuniform PointLight u_PointLight;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT\r\n\t\tuniform SpotLight u_SpotLight;\r\n\t#endif\r\n#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#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\nvoid main_castShadow()\r\n{\r\n\tgl_FragColor=packDepth(v_posViewZ);\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tfloat alpha = texture2D(u_AlbedoTexture,v_Texcoord0).w;\r\n\t\tif( alpha < u_AlphaTestValue )\r\n\t\t{\r\n\t\t\tdiscard;\r\n\t\t}\r\n\t#endif\r\n}\r\n\r\nvoid main_normal()\r\n{\t\r\n\tvec3 viewDir = normalize(v_ViewDir);\r\n\t\r\n\tvec2 uv0 = ParallaxOffset(viewDir);\r\n\t\r\n\tvec2 mg;\r\n\tvec4 albedoColor;\r\n\t#ifdef ALBEDOTEXTURE\r\n\t\tvec4 abledoTextureColor = texture2D(u_AlbedoTexture, uv0);\r\n\t\talbedoColor = abledoTextureColor * u_AlbedoColor;\r\n\t\tmg = MetallicGloss(abledoTextureColor.a, uv0);\r\n\t#else\r\n\t\talbedoColor = u_AlbedoColor;\r\n\t\tmg = MetallicGloss(1.0, uv0);\r\n\t#endif\r\n\t\r\n\t#ifdef ALPHATEST\r\n\t\tif(albedoColor.a < u_AlphaTestValue)\r\n\t\t\tdiscard;\r\n\t#endif\r\n\t\r\n\tvec3 normal = UnpackScaleNormal(uv0);\r\n \r\n\tLayaGI gi;\r\n\tgi.diffuse = u_AmbientColor * Occlusion(uv0).rgb;\r\n\tgi.specular = ReflectCubeMap(viewDir, normal);\r\n \r\n\tvec4 color = vec4(0.0);\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tcolor += PBRStandardDiectionLight(albedoColor, mg.r, mg.g, normal, viewDir, u_DirectionLight, gi);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tcolor.a = 0.0;\r\n\t\t\tcolor += PBRStandardPointLight(albedoColor, mg.r, mg.g, normal, viewDir, u_PointLight, v_PositionWorld, gi);\r\n\t\t#endif\r\n\t\t\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tcolor.a = 0.0;\r\n\t\t\tcolor += PBRStandardSpotLight(albedoColor, mg.r, mg.g, normal, viewDir, u_SpotLight, v_PositionWorld, gi);\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\tcolor.a = 0.0;\r\n\t\t\t\tcolor += PBRStandardDiectionLight(albedoColor, mg.r, mg.g, normal, viewDir, directionLight, gi);\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\tcolor.a = 0.0;\r\n\t\t\t\t\tcolor += PBRStandardPointLight(albedoColor, mg.r, mg.g, normal, viewDir, pointLight, v_PositionWorld, gi);\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\tcolor.a = 0.0;\r\n\t\t\t\t\tcolor += PBRStandardSpotLight(albedoColor, mg.r, mg.g, normal, viewDir, spotLight, v_PositionWorld, gi);\r\n\t\t\t\t\t\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\r\n\t#ifdef REFLECTMAP\r\n\t \tcolor += LayaAirStandardReflect(albedoColor,mg.r,mg.g,gi);\r\n\t#endif\r\n\r\n\t#ifdef EMISSION\r\n\t\tvec4 emissionColor = u_EmissionColor;\r\n\t\t#ifdef EMISSIONTEXTURE\r\n\t\t\temissionColor *= texture2D(u_EmissionTexture, uv0);\r\n\t\t#endif\r\n\t\tcolor.rgb += emissionColor.rgb;\r\n\t#endif\r\n\t\r\n\t#ifdef RECEIVESHADOW\r\n\t\tfloat shadowValue = 1.0;\r\n\t\t#ifdef SHADOWMAP_PSSM3\r\n\t\t\tshadowValue = getShadowPSSM3( u_shadowMap1,u_shadowMap2,u_shadowMap3,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t\t#ifdef SHADOWMAP_PSSM2\r\n\t\t\tshadowValue = getShadowPSSM2( u_shadowMap1,u_shadowMap2,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif \r\n\t\t#ifdef SHADOWMAP_PSSM1\r\n\t\t\tshadowValue = getShadowPSSM1( u_shadowMap1,v_lightMVPPos,u_shadowPSSMDistance,u_shadowPCFoffset,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t\tgl_FragColor = vec4(color.rgb * shadowValue, color.a);\r\n\t#else\r\n\t\tgl_FragColor = color;\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\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\t\t\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif \r\n}";
  28130. var PBRStandardVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec3 a_Normal;\r\nattribute vec4 a_Tangent0;\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 GPU_INSTANCE\r\n\tattribute mat4 a_WorldMat;\r\n#else\r\n\tuniform mat4 u_WorldMat;\r\n#endif\r\n\r\nuniform vec3 u_CameraPos;\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec3 v_PositionWorld;\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n #ifdef SHADOWMAP_PSSM1 \r\n\t varying vec4 v_lightMVPPos;\r\n\t uniform mat4 u_lightShadowVP[4];\r\n #endif\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_castShadow()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\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//TODO没考虑UV动画呢\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tv_Texcoord0 = a_Texcoord0;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n\tv_posViewZ = gl_Position.z;\r\n}\r\n\r\nvoid main_normal()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\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#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)||defined(REFLECTMAP)\r\n\t\tmat4 worldMat;\r\n\t\t#ifdef GPU_INSTANCE\r\n\t\t\tworldMat = a_WorldMat;\r\n\t\t#else\r\n\t\t\tworldMat = u_WorldMat;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(REFLECTMAP)\r\n\t\tmat3 worldInvMat;\r\n\t\t#ifdef BONE\r\n\t\t\tworldInvMat=inverse(mat3(worldMat*skinTransform));\r\n\t\t#else\r\n\t\t\tworldInvMat=inverse(mat3(worldMat));\r\n\t\t#endif \r\n\t\tv_Normal=a_Normal*worldInvMat;\r\n\t\t#if (defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))\r\n\t\t\tv_Tangent=a_Tangent0.xyz*worldInvMat;\r\n\t\t\tv_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)||defined(REFLECTMAP)\r\n\t\tv_PositionWorld=(worldMat*position).xyz;\r\n\t#endif\r\n\t\r\n \r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(REFLECTMAP)||defined(REFLECTMAP)\r\n\t\tv_ViewDir=u_CameraPos-v_PositionWorld;\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#ifdef RECEIVESHADOW\r\n\t\tv_posViewZ = gl_Position.w;\r\n\t\t#ifdef SHADOWMAP_PSSM1 \r\n\t\t\tv_lightMVPPos = u_lightShadowVP[0] * vec4(v_PositionWorld,1.0);\r\n\t\t#endif\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n\r\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif\r\n}";
  28131. var BloomVS = "#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}";
  28132. var BloomDownsample13PS = "#ifdef HIGHPRECISION\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}";
  28133. var BloomDownsample4PS = "#ifdef HIGHPRECISION\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}";
  28134. var BloomPrefilter13PS = "#ifdef HIGHPRECISION\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}";
  28135. var BloomPrefilter4PS = "#ifdef HIGHPRECISION\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}";
  28136. var BloomUpsampleBoxPS = "#ifdef HIGHPRECISION\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}";
  28137. var BloomUpsampleTentPS = "#ifdef HIGHPRECISION\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}";
  28138. 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}";
  28139. var CompositePS = "#ifdef HIGHPRECISION\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}";
  28140. 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}";
  28141. 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}";
  28142. 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}";
  28143. var ShadowHelperGLSL = "uniform sampler2D u_shadowMap1;\r\nuniform sampler2D u_shadowMap2;\r\nuniform sampler2D u_shadowMap3;\r\nuniform vec2\t u_shadowPCFoffset;\r\nuniform vec4 u_shadowPSSMDistance;\r\nvec4 packDepth(const in float depth)\r\n{\r\n\tconst vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);\r\n\tconst vec4 bitMask\t= vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);\r\n\tvec4 res = mod(depth*bitShift*vec4(255), vec4(256))/vec4(255);\r\n\tres -= res.xxyz * bitMask;\r\n\treturn res;\r\n}\r\nfloat unpackDepth(const in vec4 rgbaDepth)\r\n{\r\n\tconst vec4 bitShift = vec4(1.0/(256.0*256.0*256.0), 1.0/(256.0*256.0), 1.0/256.0, 1.0);\r\n\tfloat depth = dot(rgbaDepth, bitShift);\r\n\treturn depth;\r\n}\r\nfloat tex2DPCF( sampler2D shadowMap,vec2 texcoord,vec2 invsize,float zRef )\r\n{\r\n\tvec2 texelpos =texcoord / invsize;\r\n\tvec2 lerps = fract( texelpos );\r\n\tfloat sourcevals[4];\r\n\tsourcevals[0] = float( unpackDepth(texture2D(shadowMap,texcoord)) > zRef );\r\n\tsourcevals[1] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(invsize.x,0))) > zRef );\r\n\tsourcevals[2] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(0,invsize.y))) > zRef );\r\n\tsourcevals[3] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(invsize.x, invsize.y) )) > zRef );\r\n\treturn mix( mix(sourcevals[0],sourcevals[2],lerps.y),mix(sourcevals[1],sourcevals[3],lerps.y),lerps.x );\r\n}\r\nfloat getShadowPSSM3( sampler2D shadowMap1,sampler2D shadowMap2,sampler2D shadowMap3,mat4 lightShadowVP[4],vec4 pssmDistance,vec2 shadowPCFOffset,vec3 worldPos,float posViewZ,float zBias )\r\n{\r\n\tfloat value = 1.0;\r\n\tint nPSNum = int(posViewZ>pssmDistance.x);\r\n\tnPSNum += int(posViewZ>pssmDistance.y);\r\n\tnPSNum += int(posViewZ>pssmDistance.z);\r\n\t//真SB,webgl不支持在PS中直接访问数组\r\n\tmat4 lightVP;\r\n\tif( nPSNum == 0 )\r\n\t{\r\n\t\tlightVP = lightShadowVP[1];\r\n\t}\r\n\telse if( nPSNum == 1 )\r\n\t{\r\n\t\tlightVP = lightShadowVP[2];\r\n\t}\r\n\telse if( nPSNum == 2 )\r\n\t{\r\n\t\tlightVP = lightShadowVP[3];\r\n\t}\r\n\tvec4 vLightMVPPos = lightVP * vec4(worldPos,1.0);\r\n\t//为了效率,在CPU计算/2.0 + 0.5\r\n\t//vec3 vText = (vLightMVPPos.xyz / vLightMVPPos.w)/2.0 + 0.5;\r\n\tvec3 vText = vLightMVPPos.xyz / vLightMVPPos.w;\r\n\tfloat fMyZ = vText.z - zBias;\r\n\t/*\r\n\tbvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\r\n\tbool bInFrustum = all( bInFrustumVec );\r\n\tbvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\r\n\tbool bFrustumTest = all( bFrustumTestVec );\r\n\tif ( bFrustumTest ) \r\n\t*/\r\n\tif( fMyZ <= 1.0 )\r\n\t{\r\n\t\tfloat zdepth=0.0;\r\n#ifdef SHADOWMAP_PCF3\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue = value/4.0;\r\n\t\t} \r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 2 )\r\n\t\t{\r\n\t\t\tvec4 color = texture2D( shadowMap3,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n\t\t}\r\n#endif\r\n#ifdef SHADOWMAP_PCF2\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 2 )\r\n\t\t{\r\n\t\t\tvec4 color = texture2D( shadowMap3,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n\t\t}\r\n\r\n#endif\r\n#ifdef SHADOWMAP_PCF1\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvec4 color = texture2D( shadowMap2,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n\t\t}\r\n\t\telse if( nPSNum == 2 )\r\n\t\t{\r\n\t\t\tvec4 color = texture2D( shadowMap3,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n\t\t}\r\n#endif\r\n#ifdef SHADOWMAP_PCF_NO\r\n\t\tvec4 color;\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tcolor = texture2D( shadowMap1,vText.xy );\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tcolor = texture2D( shadowMap2,vText.xy );\r\n\t\t}\r\n\t\telse if( nPSNum == 2 )\r\n\t\t{\r\n\t\t\tcolor = texture2D( shadowMap3,vText.xy );\r\n\t\t}\r\n\t\tzdepth = unpackDepth(color);\r\n\t\tvalue = float(fMyZ < zdepth);\r\n#endif\r\n\t}\r\n\treturn value;\r\n}\r\nfloat getShadowPSSM2( sampler2D shadowMap1,sampler2D shadowMap2,mat4 lightShadowVP[4],vec4 pssmDistance,vec2 shadowPCFOffset,vec3 worldPos,float posViewZ,float zBias )\r\n{\r\n\tfloat value = 1.0;\r\n\tint nPSNum = int(posViewZ>pssmDistance.x);\r\n\tnPSNum += int(posViewZ>pssmDistance.y);\r\n\t//真SB,webgl不支持在PS中直接访问数组\r\n\tmat4 lightVP;\r\n\tif( nPSNum == 0 )\r\n\t{\r\n\t\tlightVP = lightShadowVP[1];\r\n\t}\r\n\telse if( nPSNum == 1 )\r\n\t{\r\n\t\tlightVP = lightShadowVP[2];\r\n\t}\r\n\tvec4 vLightMVPPos = lightVP * vec4(worldPos,1.0);\r\n\t//为了效率,在CPU计算/2.0 + 0.5\r\n\t//vec3 vText = (vLightMVPPos.xyz / vLightMVPPos.w)/2.0 + 0.5;\r\n\tvec3 vText = vLightMVPPos.xyz / vLightMVPPos.w;\r\n\tfloat fMyZ = vText.z - zBias;\r\n\t/*\r\n\tbvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\r\n\tbool bInFrustum = all( bInFrustumVec );\r\n\tbvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\r\n\tbool bFrustumTest = all( bFrustumTestVec );\r\n\tif ( bFrustumTest ) \r\n\t*/\r\n\tif( fMyZ <= 1.0 )\r\n\t{\r\n\t\tfloat zdepth=0.0;\r\n#ifdef SHADOWMAP_PCF3\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue = value/4.0;\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n#endif\r\n#ifdef SHADOWMAP_PCF2\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n#endif\r\n#ifdef SHADOWMAP_PCF1\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvec4 color = texture2D( shadowMap2,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n\t\t}\r\n#endif\r\n#ifdef SHADOWMAP_PCF_NO\r\n\t\tvec4 color;\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tcolor = texture2D( shadowMap1,vText.xy );\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tcolor = texture2D( shadowMap2,vText.xy );\r\n\t\t}\r\n\t\tzdepth = unpackDepth(color);\r\n\t\tvalue = float(fMyZ < zdepth);\r\n#endif\r\n\t}\r\n\treturn value;\r\n}\r\nfloat getShadowPSSM1( sampler2D shadowMap1,vec4 lightMVPPos,vec4 pssmDistance,vec2 shadowPCFOffset,float posViewZ,float zBias )\r\n{\r\n\tfloat value = 1.0;\r\n\tif( posViewZ < pssmDistance.x )\r\n\t{\r\n\t\tvec3 vText = lightMVPPos.xyz / lightMVPPos.w;\r\n\t\tfloat fMyZ = vText.z - zBias;\r\n\t\t/*\r\n\t\tbvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\r\n\t\tbool bInFrustum = all( bInFrustumVec );\r\n\t\tbvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\r\n\t\tbool bFrustumTest = all( bFrustumTestVec );\r\n\t\t*/\r\n\t\tif ( fMyZ <= 1.0 ) \r\n\t\t{\r\n\t\t\tfloat zdepth=0.0;\r\n#ifdef SHADOWMAP_PCF3\r\n\t\t\tvalue = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset,fMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset,fMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset,fMyZ );\r\n\t\t\tvalue = value/4.0;\r\n#endif\r\n#ifdef SHADOWMAP_PCF2\t\t\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n#endif\r\n#ifdef SHADOWMAP_PCF1\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n#endif\r\n#ifdef SHADOWMAP_PCF_NO\t\t\r\n\t\t\tvec4 color = texture2D( shadowMap1,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n#endif\r\n\t\t}\r\n\t}\r\n\treturn value;\r\n}";
  28144. var SkyBoxPS = "#ifdef HIGHPRECISION\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";
  28145. var SkyBoxVS = "#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";
  28146. var SkyBoxProceduralPS = "#ifdef HIGHPRECISION\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";
  28147. var SkyBoxProceduralVS = "#ifdef HIGHPRECISION\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";
  28148. var TrailPS = "#ifdef HIGHPRECISION\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 ";
  28149. var TrailVS = "#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\tgl_Position = u_Projection * u_View * vec4(a_Position + a_OffsetVector * getCurWidth(normalizeTime),1.0);\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n";
  28150. var UnlitPS = "#ifdef HIGHPRECISION\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";
  28151. var UnlitVS = "#include \"Lighting.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 = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\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}";
  28152. var WaterPrimaryPS = "#ifdef HIGHPRECISION\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#include \"Lighting.glsl\"\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\t\r\n\tvec3 normal1 = NormalSampleToWorldSpace1(bumpColor1, v_Tangent, v_Binormal, v_Normal);\r\n\tvec3 normal2 = NormalSampleToWorldSpace1(bumpColor2, v_Tangent, v_Binormal, v_Normal);\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";
  28153. 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}";
  28154. class ShaderVariable {
  28155. constructor() {
  28156. this.textureID = -1;
  28157. }
  28158. }
  28159. class ShaderInstance extends Laya.Resource {
  28160. constructor(vs, ps, attributeMap, uniformMap, shaderPass) {
  28161. super();
  28162. this._stateParamsMap = [];
  28163. this._uploadMark = -1;
  28164. this._uploadRenderType = -1;
  28165. this._vs = vs;
  28166. this._ps = ps;
  28167. this._attributeMap = attributeMap;
  28168. this._uniformMap = uniformMap;
  28169. this._shaderPass = shaderPass;
  28170. this._create();
  28171. this.lock = true;
  28172. }
  28173. _create() {
  28174. var gl = Laya.LayaGL.instance;
  28175. this._program = gl.createProgram();
  28176. this._vshader = this._createShader(gl, this._vs, gl.VERTEX_SHADER);
  28177. this._pshader = this._createShader(gl, this._ps, gl.FRAGMENT_SHADER);
  28178. gl.attachShader(this._program, this._vshader);
  28179. gl.attachShader(this._program, this._pshader);
  28180. for (var k in this._attributeMap)
  28181. gl.bindAttribLocation(this._program, this._attributeMap[k], k);
  28182. gl.linkProgram(this._program);
  28183. if (!Laya.Render.isConchApp && Shader3D.debugMode && !gl.getProgramParameter(this._program, gl.LINK_STATUS))
  28184. throw gl.getProgramInfoLog(this._program);
  28185. var sceneParms = [];
  28186. var cameraParms = [];
  28187. var spriteParms = [];
  28188. var materialParms = [];
  28189. var customParms = [];
  28190. this._customUniformParamsMap = [];
  28191. var nUniformNum = gl.getProgramParameter(this._program, gl.ACTIVE_UNIFORMS);
  28192. Laya.WebGLContext.useProgram(gl, this._program);
  28193. this._curActTexIndex = 0;
  28194. var one, i, n;
  28195. for (i = 0; i < nUniformNum; i++) {
  28196. var uniformData = gl.getActiveUniform(this._program, i);
  28197. var uniName = uniformData.name;
  28198. one = new ShaderVariable();
  28199. one.location = gl.getUniformLocation(this._program, uniName);
  28200. if (uniName.indexOf('[0]') > 0) {
  28201. one.name = uniName = uniName.substr(0, uniName.length - 3);
  28202. one.isArray = true;
  28203. }
  28204. else {
  28205. one.name = uniName;
  28206. one.isArray = false;
  28207. }
  28208. one.type = uniformData.type;
  28209. this._addShaderUnifiormFun(one);
  28210. var uniformPeriod = this._uniformMap[uniName];
  28211. if (uniformPeriod != null) {
  28212. one.dataOffset = Shader3D.propertyNameToID(uniName);
  28213. switch (uniformPeriod) {
  28214. case Shader3D.PERIOD_CUSTOM:
  28215. customParms.push(one);
  28216. break;
  28217. case Shader3D.PERIOD_MATERIAL:
  28218. materialParms.push(one);
  28219. break;
  28220. case Shader3D.PERIOD_SPRITE:
  28221. spriteParms.push(one);
  28222. break;
  28223. case Shader3D.PERIOD_CAMERA:
  28224. cameraParms.push(one);
  28225. break;
  28226. case Shader3D.PERIOD_SCENE:
  28227. sceneParms.push(one);
  28228. break;
  28229. default:
  28230. throw new Error("Shader3D: period is unkonw.");
  28231. }
  28232. }
  28233. }
  28234. this._sceneUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(sceneParms.length * 4 * 5 + 4, 64, true);
  28235. for (i = 0, n = sceneParms.length; i < n; i++)
  28236. this._sceneUniformParamsMap.addShaderUniform(sceneParms[i]);
  28237. this._cameraUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(cameraParms.length * 4 * 5 + 4, 64, true);
  28238. for (i = 0, n = cameraParms.length; i < n; i++)
  28239. this._cameraUniformParamsMap.addShaderUniform(cameraParms[i]);
  28240. this._spriteUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(spriteParms.length * 4 * 5 + 4, 64, true);
  28241. for (i = 0, n = spriteParms.length; i < n; i++)
  28242. this._spriteUniformParamsMap.addShaderUniform(spriteParms[i]);
  28243. this._materialUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(materialParms.length * 4 * 5 + 4, 64, true);
  28244. for (i = 0, n = materialParms.length; i < n; i++)
  28245. this._materialUniformParamsMap.addShaderUniform(materialParms[i]);
  28246. this._customUniformParamsMap.length = customParms.length;
  28247. for (i = 0, n = customParms.length; i < n; i++) {
  28248. var custom = customParms[i];
  28249. this._customUniformParamsMap[custom.dataOffset] = custom;
  28250. }
  28251. var stateMap = this._shaderPass._stateMap;
  28252. for (var s in stateMap)
  28253. this._stateParamsMap[stateMap[s]] = Shader3D.propertyNameToID(s);
  28254. }
  28255. _getRenderState(shaderDatas, stateIndex) {
  28256. var stateID = this._stateParamsMap[stateIndex];
  28257. if (stateID == null)
  28258. return null;
  28259. else
  28260. return shaderDatas[stateID];
  28261. }
  28262. _disposeResource() {
  28263. Laya.LayaGL.instance.deleteShader(this._vshader);
  28264. Laya.LayaGL.instance.deleteShader(this._pshader);
  28265. Laya.LayaGL.instance.deleteProgram(this._program);
  28266. this._vshader = this._pshader = this._program = null;
  28267. this._setGPUMemory(0);
  28268. this._curActTexIndex = 0;
  28269. }
  28270. _addShaderUnifiormFun(one) {
  28271. var gl = Laya.LayaGL.instance;
  28272. one.caller = this;
  28273. var isArray = one.isArray;
  28274. switch (one.type) {
  28275. case gl.BOOL:
  28276. one.fun = this._uniform1i;
  28277. one.uploadedValue = new Array(1);
  28278. break;
  28279. case gl.INT:
  28280. one.fun = isArray ? this._uniform1iv : this._uniform1i;
  28281. one.uploadedValue = new Array(1);
  28282. break;
  28283. case gl.FLOAT:
  28284. one.fun = isArray ? this._uniform1fv : this._uniform1f;
  28285. one.uploadedValue = new Array(1);
  28286. break;
  28287. case gl.FLOAT_VEC2:
  28288. one.fun = isArray ? this._uniform_vec2v : this._uniform_vec2;
  28289. one.uploadedValue = new Array(2);
  28290. break;
  28291. case gl.FLOAT_VEC3:
  28292. one.fun = isArray ? this._uniform_vec3v : this._uniform_vec3;
  28293. one.uploadedValue = new Array(3);
  28294. break;
  28295. case gl.FLOAT_VEC4:
  28296. one.fun = isArray ? this._uniform_vec4v : this._uniform_vec4;
  28297. one.uploadedValue = new Array(4);
  28298. break;
  28299. case gl.FLOAT_MAT2:
  28300. one.fun = this._uniformMatrix2fv;
  28301. break;
  28302. case gl.FLOAT_MAT3:
  28303. one.fun = this._uniformMatrix3fv;
  28304. break;
  28305. case gl.FLOAT_MAT4:
  28306. one.fun = isArray ? this._uniformMatrix4fv : this._uniformMatrix4f;
  28307. break;
  28308. case gl.SAMPLER_2D:
  28309. gl.uniform1i(one.location, this._curActTexIndex);
  28310. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  28311. one.fun = this._uniform_sampler2D;
  28312. break;
  28313. case 0x8b5f:
  28314. gl.uniform1i(one.location, this._curActTexIndex);
  28315. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  28316. one.fun = this._uniform_sampler3D;
  28317. break;
  28318. case gl.SAMPLER_CUBE:
  28319. gl.uniform1i(one.location, this._curActTexIndex);
  28320. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  28321. one.fun = this._uniform_samplerCube;
  28322. break;
  28323. default:
  28324. throw new Error("compile shader err!");
  28325. break;
  28326. }
  28327. }
  28328. _createShader(gl, str, type) {
  28329. var shader = gl.createShader(type);
  28330. gl.shaderSource(shader, str);
  28331. gl.compileShader(shader);
  28332. if (Shader3D.debugMode && !gl.getShaderParameter(shader, gl.COMPILE_STATUS))
  28333. throw gl.getShaderInfoLog(shader);
  28334. return shader;
  28335. }
  28336. _uniform1f(one, value) {
  28337. var uploadedValue = one.uploadedValue;
  28338. if (uploadedValue[0] !== value) {
  28339. Laya.LayaGL.instance.uniform1f(one.location, uploadedValue[0] = value);
  28340. return 1;
  28341. }
  28342. return 0;
  28343. }
  28344. _uniform1fv(one, value) {
  28345. if (value.length < 4) {
  28346. var uploadedValue = one.uploadedValue;
  28347. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  28348. Laya.LayaGL.instance.uniform1fv(one.location, value);
  28349. uploadedValue[0] = value[0];
  28350. uploadedValue[1] = value[1];
  28351. uploadedValue[2] = value[2];
  28352. uploadedValue[3] = value[3];
  28353. return 1;
  28354. }
  28355. return 0;
  28356. }
  28357. else {
  28358. Laya.LayaGL.instance.uniform1fv(one.location, value);
  28359. return 1;
  28360. }
  28361. }
  28362. _uniform_vec2(one, v) {
  28363. var uploadedValue = one.uploadedValue;
  28364. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y) {
  28365. Laya.LayaGL.instance.uniform2f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y);
  28366. return 1;
  28367. }
  28368. return 0;
  28369. }
  28370. _uniform_vec2v(one, value) {
  28371. if (value.length < 2) {
  28372. var uploadedValue = one.uploadedValue;
  28373. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  28374. Laya.LayaGL.instance.uniform2fv(one.location, value);
  28375. uploadedValue[0] = value[0];
  28376. uploadedValue[1] = value[1];
  28377. uploadedValue[2] = value[2];
  28378. uploadedValue[3] = value[3];
  28379. return 1;
  28380. }
  28381. return 0;
  28382. }
  28383. else {
  28384. Laya.LayaGL.instance.uniform2fv(one.location, value);
  28385. return 1;
  28386. }
  28387. }
  28388. _uniform_vec3(one, v) {
  28389. var uploadedValue = one.uploadedValue;
  28390. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y || uploadedValue[2] !== v.z) {
  28391. Laya.LayaGL.instance.uniform3f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y, uploadedValue[2] = v.z);
  28392. return 1;
  28393. }
  28394. return 0;
  28395. }
  28396. _uniform_vec3v(one, v) {
  28397. Laya.LayaGL.instance.uniform3fv(one.location, v);
  28398. return 1;
  28399. }
  28400. _uniform_vec4(one, v) {
  28401. var uploadedValue = one.uploadedValue;
  28402. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y || uploadedValue[2] !== v.z || uploadedValue[3] !== v.w) {
  28403. Laya.LayaGL.instance.uniform4f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y, uploadedValue[2] = v.z, uploadedValue[3] = v.w);
  28404. return 1;
  28405. }
  28406. return 0;
  28407. }
  28408. _uniform_vec4v(one, v) {
  28409. Laya.LayaGL.instance.uniform4fv(one.location, v);
  28410. return 1;
  28411. }
  28412. _uniformMatrix2fv(one, value) {
  28413. Laya.LayaGL.instance.uniformMatrix2fv(one.location, false, value);
  28414. return 1;
  28415. }
  28416. _uniformMatrix3fv(one, value) {
  28417. Laya.LayaGL.instance.uniformMatrix3fv(one.location, false, value);
  28418. return 1;
  28419. }
  28420. _uniformMatrix4f(one, m) {
  28421. var value = m.elements;
  28422. Laya.LayaGL.instance.uniformMatrix4fv(one.location, false, value);
  28423. return 1;
  28424. }
  28425. _uniformMatrix4fv(one, m) {
  28426. Laya.LayaGL.instance.uniformMatrix4fv(one.location, false, m);
  28427. return 1;
  28428. }
  28429. _uniform1i(one, value) {
  28430. var uploadedValue = one.uploadedValue;
  28431. if (uploadedValue[0] !== value) {
  28432. Laya.LayaGL.instance.uniform1i(one.location, uploadedValue[0] = value);
  28433. return 1;
  28434. }
  28435. return 0;
  28436. }
  28437. _uniform1iv(one, value) {
  28438. Laya.LayaGL.instance.uniform1iv(one.location, value);
  28439. return 1;
  28440. }
  28441. _uniform_ivec2(one, value) {
  28442. var uploadedValue = one.uploadedValue;
  28443. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1]) {
  28444. Laya.LayaGL.instance.uniform2i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1]);
  28445. return 1;
  28446. }
  28447. return 0;
  28448. }
  28449. _uniform_ivec2v(one, value) {
  28450. Laya.LayaGL.instance.uniform2iv(one.location, value);
  28451. return 1;
  28452. }
  28453. _uniform_vec3i(one, value) {
  28454. var uploadedValue = one.uploadedValue;
  28455. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2]) {
  28456. Laya.LayaGL.instance.uniform3i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1], uploadedValue[2] = value[2]);
  28457. return 1;
  28458. }
  28459. return 0;
  28460. }
  28461. _uniform_vec3vi(one, value) {
  28462. Laya.LayaGL.instance.uniform3iv(one.location, value);
  28463. return 1;
  28464. }
  28465. _uniform_vec4i(one, value) {
  28466. var uploadedValue = one.uploadedValue;
  28467. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  28468. Laya.LayaGL.instance.uniform4i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1], uploadedValue[2] = value[2], uploadedValue[3] = value[3]);
  28469. return 1;
  28470. }
  28471. return 0;
  28472. }
  28473. _uniform_vec4vi(one, value) {
  28474. Laya.LayaGL.instance.uniform4iv(one.location, value);
  28475. return 1;
  28476. }
  28477. _uniform_sampler2D(one, texture) {
  28478. var value = texture._getSource() || texture.defaulteTexture._getSource();
  28479. var gl = Laya.LayaGL.instance;
  28480. Laya.WebGLContext.activeTexture(gl, one.textureID);
  28481. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_2D, value);
  28482. return 0;
  28483. }
  28484. _uniform_sampler3D(one, texture) {
  28485. var value = texture._getSource() || texture.defaulteTexture._getSource();
  28486. var gl = Laya.LayaGL.instance;
  28487. Laya.WebGLContext.activeTexture(gl, one.textureID);
  28488. Laya.WebGLContext.bindTexture(gl, WebGL2RenderingContext.TEXTURE_3D, value);
  28489. return 0;
  28490. }
  28491. _uniform_samplerCube(one, texture) {
  28492. var value = texture._getSource() || texture.defaulteTexture._getSource();
  28493. var gl = Laya.LayaGL.instance;
  28494. Laya.WebGLContext.activeTexture(gl, one.textureID);
  28495. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_CUBE_MAP, value);
  28496. return 0;
  28497. }
  28498. bind() {
  28499. return Laya.WebGLContext.useProgram(Laya.LayaGL.instance, this._program);
  28500. }
  28501. uploadUniforms(shaderUniform, shaderDatas, uploadUnTexture) {
  28502. Laya.Stat.shaderCall += Laya.LayaGLRunner.uploadShaderUniforms(Laya.LayaGL.instance, shaderUniform, shaderDatas, uploadUnTexture);
  28503. }
  28504. uploadRenderStateBlendDepth(shaderDatas) {
  28505. var gl = Laya.LayaGL.instance;
  28506. var renderState = this._shaderPass.renderState;
  28507. var datas = shaderDatas.getData();
  28508. var depthWrite = this._getRenderState(datas, Shader3D.RENDER_STATE_DEPTH_WRITE);
  28509. var depthTest = this._getRenderState(datas, Shader3D.RENDER_STATE_DEPTH_TEST);
  28510. var blend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND);
  28511. depthWrite == null && (depthWrite = renderState.depthWrite);
  28512. depthTest == null && (depthTest = renderState.depthTest);
  28513. blend == null && (blend = renderState.blend);
  28514. Laya.WebGLContext.setDepthMask(gl, depthWrite);
  28515. if (depthTest === RenderState.DEPTHTEST_OFF)
  28516. Laya.WebGLContext.setDepthTest(gl, false);
  28517. else {
  28518. Laya.WebGLContext.setDepthTest(gl, true);
  28519. Laya.WebGLContext.setDepthFunc(gl, depthTest);
  28520. }
  28521. switch (blend) {
  28522. case RenderState.BLEND_DISABLE:
  28523. Laya.WebGLContext.setBlend(gl, false);
  28524. break;
  28525. case RenderState.BLEND_ENABLE_ALL:
  28526. var blendEquation = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION);
  28527. var srcBlend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC);
  28528. var dstBlend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST);
  28529. blendEquation == null && (blendEquation = renderState.blendEquation);
  28530. srcBlend == null && (srcBlend = renderState.srcBlend);
  28531. dstBlend == null && (dstBlend = renderState.dstBlend);
  28532. Laya.WebGLContext.setBlend(gl, true);
  28533. Laya.WebGLContext.setBlendEquation(gl, blendEquation);
  28534. Laya.WebGLContext.setBlendFunc(gl, srcBlend, dstBlend);
  28535. break;
  28536. case RenderState.BLEND_ENABLE_SEPERATE:
  28537. var blendEquationRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION_RGB);
  28538. var blendEquationAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION_ALPHA);
  28539. var srcRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC_RGB);
  28540. var dstRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST_RGB);
  28541. var srcAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC_ALPHA);
  28542. var dstAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST_ALPHA);
  28543. blendEquationRGB == null && (blendEquationRGB = renderState.blendEquationRGB);
  28544. blendEquationAlpha == null && (blendEquationAlpha = renderState.blendEquationAlpha);
  28545. srcRGB == null && (srcRGB = renderState.srcBlendRGB);
  28546. dstRGB == null && (dstRGB = renderState.dstBlendRGB);
  28547. srcAlpha == null && (srcAlpha = renderState.srcBlendAlpha);
  28548. dstAlpha == null && (dstAlpha = renderState.dstBlendAlpha);
  28549. Laya.WebGLContext.setBlend(gl, true);
  28550. Laya.WebGLContext.setBlendEquationSeparate(gl, blendEquationRGB, blendEquationAlpha);
  28551. Laya.WebGLContext.setBlendFuncSeperate(gl, srcRGB, dstRGB, srcAlpha, dstAlpha);
  28552. break;
  28553. }
  28554. }
  28555. uploadRenderStateFrontFace(shaderDatas, isTarget, invertFront) {
  28556. var gl = Laya.LayaGL.instance;
  28557. var renderState = this._shaderPass.renderState;
  28558. var datas = shaderDatas.getData();
  28559. var cull = this._getRenderState(datas, Shader3D.RENDER_STATE_CULL);
  28560. cull == null && (cull = renderState.cull);
  28561. var forntFace;
  28562. switch (cull) {
  28563. case RenderState.CULL_NONE:
  28564. Laya.WebGLContext.setCullFace(gl, false);
  28565. break;
  28566. case RenderState.CULL_FRONT:
  28567. Laya.WebGLContext.setCullFace(gl, true);
  28568. if (isTarget) {
  28569. if (invertFront)
  28570. forntFace = gl.CCW;
  28571. else
  28572. forntFace = gl.CW;
  28573. }
  28574. else {
  28575. if (invertFront)
  28576. forntFace = gl.CW;
  28577. else
  28578. forntFace = gl.CCW;
  28579. }
  28580. Laya.WebGLContext.setFrontFace(gl, forntFace);
  28581. break;
  28582. case RenderState.CULL_BACK:
  28583. Laya.WebGLContext.setCullFace(gl, true);
  28584. if (isTarget) {
  28585. if (invertFront)
  28586. forntFace = gl.CW;
  28587. else
  28588. forntFace = gl.CCW;
  28589. }
  28590. else {
  28591. if (invertFront)
  28592. forntFace = gl.CCW;
  28593. else
  28594. forntFace = gl.CW;
  28595. }
  28596. Laya.WebGLContext.setFrontFace(gl, forntFace);
  28597. break;
  28598. }
  28599. }
  28600. uploadCustomUniform(index, data) {
  28601. Laya.Stat.shaderCall += Laya.LayaGLRunner.uploadCustomUniform(Laya.LayaGL.instance, this._customUniformParamsMap, index, data);
  28602. }
  28603. _uniformMatrix2fvForNative(one, value) {
  28604. Laya.LayaGL.instance.uniformMatrix2fvEx(one.location, false, value);
  28605. return 1;
  28606. }
  28607. _uniformMatrix3fvForNative(one, value) {
  28608. Laya.LayaGL.instance.uniformMatrix3fvEx(one.location, false, value);
  28609. return 1;
  28610. }
  28611. _uniformMatrix4fvForNative(one, m) {
  28612. Laya.LayaGL.instance.uniformMatrix4fvEx(one.location, false, m);
  28613. return 1;
  28614. }
  28615. }
  28616. class ShaderPass extends Laya.ShaderCompile {
  28617. constructor(owner, vs, ps, stateMap) {
  28618. super(vs, ps, null);
  28619. this._cacheSharders = {};
  28620. this._cacheShaderHierarchy = 1;
  28621. this._renderState = new RenderState();
  28622. this._validDefine = new DefineDatas();
  28623. this._owner = owner;
  28624. this._stateMap = stateMap;
  28625. for (var k in this.defs)
  28626. this._validDefine.add(Shader3D.getDefineByName(k));
  28627. }
  28628. get renderState() {
  28629. return this._renderState;
  28630. }
  28631. _compileToTree(parent, lines, start, includefiles, defs) {
  28632. var node, preNode;
  28633. var text, name, fname;
  28634. var ofs, words, noUseNode;
  28635. var i, n, j;
  28636. for (i = start; i < lines.length; i++) {
  28637. text = lines[i];
  28638. if (text.length < 1)
  28639. continue;
  28640. ofs = text.indexOf("//");
  28641. if (ofs === 0)
  28642. continue;
  28643. if (ofs >= 0)
  28644. text = text.substr(0, ofs);
  28645. node = noUseNode || new Laya.ShaderNode(includefiles);
  28646. noUseNode = null;
  28647. node.text = text;
  28648. if ((ofs = text.indexOf("#")) >= 0) {
  28649. name = "#";
  28650. for (j = ofs + 1, n = text.length; j < n; j++) {
  28651. var c = text.charAt(j);
  28652. if (c === ' ' || c === '\t' || c === '?')
  28653. break;
  28654. name += c;
  28655. }
  28656. node.name = name;
  28657. switch (name) {
  28658. case "#ifdef":
  28659. case "#ifndef":
  28660. node.setParent(parent);
  28661. parent = node;
  28662. if (defs) {
  28663. words = text.substr(j).split(Laya.ShaderCompile._splitToWordExps3);
  28664. for (j = 0; j < words.length; j++) {
  28665. text = words[j];
  28666. text.length && (defs[text] = true);
  28667. }
  28668. }
  28669. continue;
  28670. case "#if":
  28671. case "#elif":
  28672. node.setParent(parent);
  28673. parent = node;
  28674. if (defs) {
  28675. words = text.substr(j).split(Laya.ShaderCompile._splitToWordExps3);
  28676. for (j = 0; j < words.length; j++) {
  28677. text = words[j];
  28678. text.length && text != "defined" && (defs[text] = true);
  28679. }
  28680. }
  28681. continue;
  28682. case "#else":
  28683. parent = parent.parent;
  28684. preNode = parent.childs[parent.childs.length - 1];
  28685. node.setParent(parent);
  28686. parent = node;
  28687. continue;
  28688. case "#endif":
  28689. parent = parent.parent;
  28690. preNode = parent.childs[parent.childs.length - 1];
  28691. node.setParent(parent);
  28692. continue;
  28693. case "#include":
  28694. words = Laya.ShaderCompile.splitToWords(text, null);
  28695. var inlcudeFile = Laya.ShaderCompile.includes[words[1]];
  28696. if (!inlcudeFile) {
  28697. throw "ShaderCompile error no this include file:" + words[1];
  28698. }
  28699. if ((ofs = words[0].indexOf("?")) < 0) {
  28700. node.setParent(parent);
  28701. text = inlcudeFile.getWith(words[2] == 'with' ? words[3] : null);
  28702. this._compileToTree(node, text.split('\n'), 0, includefiles, defs);
  28703. node.text = "";
  28704. continue;
  28705. }
  28706. node.setCondition(words[0].substr(ofs + 1), Laya.ShaderCompile.IFDEF_YES);
  28707. node.text = inlcudeFile.getWith(words[2] == 'with' ? words[3] : null);
  28708. break;
  28709. case "#import":
  28710. words = Laya.ShaderCompile.splitToWords(text, null);
  28711. fname = words[1];
  28712. includefiles.push({ node: node, file: Laya.ShaderCompile.includes[fname], ofs: node.text.length });
  28713. continue;
  28714. }
  28715. }
  28716. else {
  28717. preNode = parent.childs[parent.childs.length - 1];
  28718. if (preNode && !preNode.name) {
  28719. includefiles.length > 0 && Laya.ShaderCompile.splitToWords(text, preNode);
  28720. noUseNode = node;
  28721. preNode.text += "\n" + text;
  28722. continue;
  28723. }
  28724. includefiles.length > 0 && Laya.ShaderCompile.splitToWords(text, node);
  28725. }
  28726. node.setParent(parent);
  28727. }
  28728. }
  28729. _resizeCacheShaderMap(cacheMap, hierarchy, resizeLength) {
  28730. var end = this._cacheShaderHierarchy - 1;
  28731. if (hierarchy == end) {
  28732. for (var k in cacheMap) {
  28733. var shader = cacheMap[k];
  28734. for (var i = 0, n = resizeLength - end; i < n; i++) {
  28735. if (i == n - 1)
  28736. cacheMap[0] = shader;
  28737. else
  28738. cacheMap = cacheMap[i == 0 ? k : 0] = {};
  28739. }
  28740. }
  28741. this._cacheShaderHierarchy = resizeLength;
  28742. }
  28743. else {
  28744. for (var k in cacheMap)
  28745. this._resizeCacheShaderMap(cacheMap[k], ++hierarchy, resizeLength);
  28746. }
  28747. }
  28748. withCompile(compileDefine) {
  28749. compileDefine._intersectionDefineDatas(this._validDefine);
  28750. var cacheShaders = this._cacheSharders;
  28751. var maskLength = compileDefine._length;
  28752. if (maskLength > this._cacheShaderHierarchy) {
  28753. this._resizeCacheShaderMap(cacheShaders, 0, maskLength);
  28754. this._cacheShaderHierarchy = maskLength;
  28755. }
  28756. var mask = compileDefine._mask;
  28757. var endIndex = compileDefine._length - 1;
  28758. var maxEndIndex = this._cacheShaderHierarchy - 1;
  28759. for (var i = 0; i < maxEndIndex; i++) {
  28760. var subMask = endIndex < i ? 0 : mask[i];
  28761. var subCacheShaders = cacheShaders[subMask];
  28762. (subCacheShaders) || (cacheShaders[subMask] = subCacheShaders = {});
  28763. cacheShaders = subCacheShaders;
  28764. }
  28765. var cacheKey = endIndex < maxEndIndex ? 0 : mask[maxEndIndex];
  28766. var shader = cacheShaders[cacheKey];
  28767. if (shader)
  28768. return shader;
  28769. var defineString = ShaderPass._defineString;
  28770. Shader3D._getNamesByDefineData(compileDefine, defineString);
  28771. var config = Config3D._config;
  28772. var clusterSlices = config.lightClusterCount;
  28773. var defMap = {};
  28774. var defineStr = "#define MAX_LIGHT_COUNT " + config.maxLightCount + "\n";
  28775. defineStr += "#define MAX_LIGHT_COUNT_PER_CLUSTER " + config._maxAreaLightCountPerClusterAverage + "\n";
  28776. defineStr += "#define CLUSTER_X_COUNT " + clusterSlices.x + "\n";
  28777. defineStr += "#define CLUSTER_Y_COUNT " + clusterSlices.y + "\n";
  28778. defineStr += "#define CLUSTER_Z_COUNT " + clusterSlices.z + "\n";
  28779. for (var i = 0, n = defineString.length; i < n; i++) {
  28780. var def = defineString[i];
  28781. defineStr += "#define " + def + "\n";
  28782. defMap[def] = true;
  28783. }
  28784. var vs = this._VS.toscript(defMap, []);
  28785. var vsVersion = '';
  28786. if (vs[0].indexOf('#version') == 0) {
  28787. vsVersion = vs[0] + '\n';
  28788. vs.shift();
  28789. }
  28790. var ps = this._PS.toscript(defMap, []);
  28791. var psVersion = '';
  28792. if (ps[0].indexOf('#version') == 0) {
  28793. psVersion = ps[0] + '\n';
  28794. ps.shift();
  28795. }
  28796. shader = new ShaderInstance(vsVersion + defineStr + vs.join('\n'), psVersion + defineStr + ps.join('\n'), this._owner._attributeMap || this._owner._owner._attributeMap, this._owner._uniformMap || this._owner._owner._uniformMap, this);
  28797. cacheShaders[cacheKey] = shader;
  28798. if (Shader3D.debugMode) {
  28799. var defStr = "";
  28800. var defMask = "";
  28801. if (Laya.WebGL.shaderHighPrecision) {
  28802. compileDefine.remove(Shader3D.SHADERDEFINE_HIGHPRECISION);
  28803. var index = defineString.indexOf("HIGHPRECISION");
  28804. (index !== -1) && (defineString.splice(index, 1));
  28805. }
  28806. if (!config._multiLighting) {
  28807. compileDefine.remove(Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING);
  28808. var index = defineString.indexOf("LEGACYSINGLELIGHTING");
  28809. (index !== -1) && (defineString.splice(index, 1));
  28810. }
  28811. for (var i = 0, n = compileDefine._length; i < n; i++)
  28812. (i == n - 1) ? defMask += mask[i] : defMask += mask[i] + ",";
  28813. for (var i = 0, n = defineString.length; i < n; i++)
  28814. (i == n - 1) ? defStr += defineString[i] : defStr += defineString[i] + ",";
  28815. // 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");
  28816. }
  28817. return shader;
  28818. }
  28819. }
  28820. ShaderPass._defineString = [];
  28821. class SubShader {
  28822. constructor(attributeMap, uniformMap) {
  28823. this._flags = {};
  28824. this._passes = [];
  28825. this._attributeMap = attributeMap;
  28826. this._uniformMap = uniformMap;
  28827. }
  28828. setFlag(key, value) {
  28829. if (value)
  28830. this._flags[key] = value;
  28831. else
  28832. delete this._flags[key];
  28833. }
  28834. getFlag(key) {
  28835. return this._flags[key];
  28836. }
  28837. addShaderPass(vs, ps, stateMap = null) {
  28838. var shaderPass = new ShaderPass(this, vs, ps, stateMap);
  28839. this._passes.push(shaderPass);
  28840. return shaderPass;
  28841. }
  28842. }
  28843. class ShaderInit3D {
  28844. constructor() {
  28845. }
  28846. static __init__() {
  28847. Shader3D.SHADERDEFINE_HIGHPRECISION = Shader3D.getDefineByName("HIGHPRECISION");
  28848. Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING = Shader3D.getDefineByName("LEGACYSINGLELIGHTING");
  28849. Shader3D.addInclude("Lighting.glsl", LightingGLSL);
  28850. Shader3D.addInclude("ShadowHelper.glsl", ShadowHelperGLSL);
  28851. Shader3D.addInclude("BRDF.glsl", BRDFGLSL);
  28852. Shader3D.addInclude("PBRUtils.glsl", PBRUtilsGLSL);
  28853. Shader3D.addInclude("PBRStandardLighting.glsl", PBRStandardLightingGLSL);
  28854. Shader3D.addInclude("PBRSpecularLighting.glsl", PBRSpecularLightingGLSL);
  28855. Shader3D.addInclude("Colors.glsl", ColorsGLSL);
  28856. Shader3D.addInclude("Sampling.glsl", SamplingGLSL);
  28857. Shader3D.addInclude("StdLib.glsl", StdLibGLSL);
  28858. var attributeMap = {
  28859. 'a_Position': VertexMesh.MESH_POSITION0,
  28860. 'a_Color': VertexMesh.MESH_COLOR0,
  28861. 'a_Normal': VertexMesh.MESH_NORMAL0,
  28862. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  28863. 'a_Texcoord1': VertexMesh.MESH_TEXTURECOORDINATE1,
  28864. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  28865. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  28866. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  28867. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  28868. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  28869. };
  28870. var uniformMap = {
  28871. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  28872. 'u_DiffuseTexture': Shader3D.PERIOD_MATERIAL,
  28873. 'u_SpecularTexture': Shader3D.PERIOD_MATERIAL,
  28874. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  28875. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  28876. 'u_DiffuseColor': Shader3D.PERIOD_MATERIAL,
  28877. 'u_MaterialSpecular': Shader3D.PERIOD_MATERIAL,
  28878. 'u_Shininess': Shader3D.PERIOD_MATERIAL,
  28879. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  28880. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  28881. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  28882. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  28883. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  28884. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  28885. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  28886. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  28887. 'u_View': Shader3D.PERIOD_CAMERA,
  28888. 'u_ReflectTexture': Shader3D.PERIOD_SCENE,
  28889. 'u_ReflectIntensity': Shader3D.PERIOD_SCENE,
  28890. 'u_FogStart': Shader3D.PERIOD_SCENE,
  28891. 'u_FogRange': Shader3D.PERIOD_SCENE,
  28892. 'u_FogColor': Shader3D.PERIOD_SCENE,
  28893. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  28894. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  28895. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  28896. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  28897. 'u_shadowMap1': Shader3D.PERIOD_SCENE,
  28898. 'u_shadowMap2': Shader3D.PERIOD_SCENE,
  28899. 'u_shadowMap3': Shader3D.PERIOD_SCENE,
  28900. 'u_shadowPSSMDistance': Shader3D.PERIOD_SCENE,
  28901. 'u_lightShadowVP': Shader3D.PERIOD_SCENE,
  28902. 'u_shadowPCFoffset': Shader3D.PERIOD_SCENE,
  28903. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  28904. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  28905. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  28906. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  28907. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  28908. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  28909. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  28910. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  28911. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  28912. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  28913. };
  28914. var stateMap = {
  28915. 's_Cull': Shader3D.RENDER_STATE_CULL,
  28916. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  28917. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  28918. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  28919. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  28920. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  28921. };
  28922. var shader = Shader3D.add("BLINNPHONG", null, null, true);
  28923. var subShader = new SubShader(attributeMap, uniformMap);
  28924. shader.addSubShader(subShader);
  28925. subShader.addShaderPass(MeshBlinnPhongVS, MeshBlinnPhongPS, stateMap);
  28926. attributeMap = {
  28927. 'a_Position': VertexMesh.MESH_POSITION0,
  28928. 'a_Color': VertexMesh.MESH_COLOR0
  28929. };
  28930. uniformMap = {
  28931. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  28932. 'u_Color': Shader3D.PERIOD_MATERIAL
  28933. };
  28934. stateMap = {
  28935. 's_Cull': Shader3D.RENDER_STATE_CULL,
  28936. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  28937. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  28938. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  28939. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  28940. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  28941. };
  28942. shader = Shader3D.add("LineShader");
  28943. subShader = new SubShader(attributeMap, uniformMap);
  28944. shader.addSubShader(subShader);
  28945. subShader.addShaderPass(lineVS, linePS, stateMap);
  28946. attributeMap = {
  28947. 'a_Position': VertexMesh.MESH_POSITION0,
  28948. 'a_Normal': VertexMesh.MESH_NORMAL0,
  28949. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  28950. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  28951. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  28952. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  28953. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  28954. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  28955. };
  28956. uniformMap = {
  28957. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  28958. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  28959. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  28960. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  28961. 'u_View': Shader3D.PERIOD_CAMERA,
  28962. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  28963. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  28964. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  28965. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  28966. 'u_EmissionColor': Shader3D.PERIOD_MATERIAL,
  28967. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  28968. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  28969. 'u_ParallaxTexture': Shader3D.PERIOD_MATERIAL,
  28970. 'u_MetallicGlossTexture': Shader3D.PERIOD_MATERIAL,
  28971. 'u_OcclusionTexture': Shader3D.PERIOD_MATERIAL,
  28972. 'u_EmissionTexture': Shader3D.PERIOD_MATERIAL,
  28973. 'u_metallic': Shader3D.PERIOD_MATERIAL,
  28974. 'u_smoothness': Shader3D.PERIOD_MATERIAL,
  28975. 'u_smoothnessScale': Shader3D.PERIOD_MATERIAL,
  28976. 'u_occlusionStrength': Shader3D.PERIOD_MATERIAL,
  28977. 'u_normalScale': Shader3D.PERIOD_MATERIAL,
  28978. 'u_parallaxScale': Shader3D.PERIOD_MATERIAL,
  28979. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  28980. 'u_ReflectTexture': Shader3D.PERIOD_SCENE,
  28981. 'u_ReflectIntensity': Shader3D.PERIOD_SCENE,
  28982. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  28983. 'u_shadowMap1': Shader3D.PERIOD_SCENE,
  28984. 'u_shadowMap2': Shader3D.PERIOD_SCENE,
  28985. 'u_shadowMap3': Shader3D.PERIOD_SCENE,
  28986. 'u_shadowPSSMDistance': Shader3D.PERIOD_SCENE,
  28987. 'u_lightShadowVP': Shader3D.PERIOD_SCENE,
  28988. 'u_shadowPCFoffset': Shader3D.PERIOD_SCENE,
  28989. 'u_FogStart': Shader3D.PERIOD_SCENE,
  28990. 'u_FogRange': Shader3D.PERIOD_SCENE,
  28991. 'u_FogColor': Shader3D.PERIOD_SCENE,
  28992. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  28993. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  28994. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  28995. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  28996. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  28997. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  28998. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  28999. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  29000. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  29001. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  29002. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  29003. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  29004. 'u_SpotLight.color': Shader3D.PERIOD_SCENE,
  29005. };
  29006. stateMap = {
  29007. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29008. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29009. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29010. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29011. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29012. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29013. };
  29014. shader = Shader3D.add("PBRStandard", null, null, true);
  29015. subShader = new SubShader(attributeMap, uniformMap);
  29016. shader.addSubShader(subShader);
  29017. subShader.addShaderPass(PBRStandardVS, PBRStandardPS, stateMap);
  29018. attributeMap = {
  29019. 'a_Position': VertexMesh.MESH_POSITION0,
  29020. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29021. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  29022. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29023. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29024. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29025. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  29026. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  29027. };
  29028. uniformMap = {
  29029. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29030. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29031. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29032. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29033. 'u_View': Shader3D.PERIOD_CAMERA,
  29034. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  29035. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  29036. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29037. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29038. 'u_SpecularColor': Shader3D.PERIOD_MATERIAL,
  29039. 'u_EmissionColor': Shader3D.PERIOD_MATERIAL,
  29040. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29041. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  29042. 'u_ParallaxTexture': Shader3D.PERIOD_MATERIAL,
  29043. 'u_SpecularTexture': Shader3D.PERIOD_MATERIAL,
  29044. 'u_OcclusionTexture': Shader3D.PERIOD_MATERIAL,
  29045. 'u_EmissionTexture': Shader3D.PERIOD_MATERIAL,
  29046. 'u_smoothness': Shader3D.PERIOD_MATERIAL,
  29047. 'u_smoothnessScale': Shader3D.PERIOD_MATERIAL,
  29048. 'u_occlusionStrength': Shader3D.PERIOD_MATERIAL,
  29049. 'u_normalScale': Shader3D.PERIOD_MATERIAL,
  29050. 'u_parallaxScale': Shader3D.PERIOD_MATERIAL,
  29051. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29052. 'u_ReflectTexture': Shader3D.PERIOD_SCENE,
  29053. 'u_ReflectIntensity': Shader3D.PERIOD_SCENE,
  29054. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  29055. 'u_shadowMap1': Shader3D.PERIOD_SCENE,
  29056. 'u_shadowMap2': Shader3D.PERIOD_SCENE,
  29057. 'u_shadowMap3': Shader3D.PERIOD_SCENE,
  29058. 'u_shadowPSSMDistance': Shader3D.PERIOD_SCENE,
  29059. 'u_lightShadowVP': Shader3D.PERIOD_SCENE,
  29060. 'u_shadowPCFoffset': Shader3D.PERIOD_SCENE,
  29061. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29062. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29063. 'u_FogColor': Shader3D.PERIOD_SCENE,
  29064. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  29065. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  29066. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  29067. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  29068. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  29069. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  29070. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  29071. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  29072. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  29073. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  29074. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  29075. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  29076. 'u_SpotLight.color': Shader3D.PERIOD_SCENE,
  29077. };
  29078. stateMap = {
  29079. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29080. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29081. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29082. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29083. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29084. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29085. };
  29086. shader = Shader3D.add("PBRSpecular", null, null, true);
  29087. subShader = new SubShader(attributeMap, uniformMap);
  29088. shader.addSubShader(subShader);
  29089. subShader.addShaderPass(PBRSpecularVS, PBRSpecularPS, stateMap);
  29090. attributeMap = {
  29091. 'a_Position': VertexMesh.MESH_POSITION0,
  29092. 'a_Color': VertexMesh.MESH_COLOR0,
  29093. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29094. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29095. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29096. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0
  29097. };
  29098. uniformMap = {
  29099. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29100. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29101. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29102. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29103. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29104. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29105. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29106. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29107. 'u_FogColor': Shader3D.PERIOD_SCENE
  29108. };
  29109. stateMap = {
  29110. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29111. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29112. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29113. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29114. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29115. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29116. };
  29117. shader = Shader3D.add("Unlit", null, null, true);
  29118. subShader = new SubShader(attributeMap, uniformMap);
  29119. shader.addSubShader(subShader);
  29120. subShader.addShaderPass(UnlitVS, UnlitPS, stateMap);
  29121. attributeMap = {
  29122. 'a_Position': VertexMesh.MESH_POSITION0,
  29123. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29124. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29125. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29126. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0
  29127. };
  29128. uniformMap = {
  29129. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29130. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29131. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29132. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29133. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29134. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29135. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29136. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29137. 'u_FogColor': Shader3D.PERIOD_SCENE
  29138. };
  29139. stateMap = {
  29140. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29141. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29142. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29143. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29144. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29145. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29146. };
  29147. shader = Shader3D.add("Effect", null, null, true);
  29148. subShader = new SubShader(attributeMap, uniformMap);
  29149. shader.addSubShader(subShader);
  29150. subShader.addShaderPass(EffectVS, EffectPS, stateMap);
  29151. attributeMap = {
  29152. 'a_CornerTextureCoordinate': VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0,
  29153. 'a_MeshPosition': VertexShuriKenParticle.PARTICLE_POSITION0,
  29154. 'a_MeshColor': VertexShuriKenParticle.PARTICLE_COLOR0,
  29155. 'a_MeshTextureCoordinate': VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0,
  29156. 'a_ShapePositionStartLifeTime': VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME,
  29157. 'a_DirectionTime': VertexShuriKenParticle.PARTICLE_DIRECTIONTIME,
  29158. 'a_StartColor': VertexShuriKenParticle.PARTICLE_STARTCOLOR0,
  29159. 'a_EndColor': VertexShuriKenParticle.PARTICLE_ENDCOLOR0,
  29160. 'a_StartSize': VertexShuriKenParticle.PARTICLE_STARTSIZE,
  29161. 'a_StartRotation0': VertexShuriKenParticle.PARTICLE_STARTROTATION,
  29162. 'a_StartSpeed': VertexShuriKenParticle.PARTICLE_STARTSPEED,
  29163. 'a_Random0': VertexShuriKenParticle.PARTICLE_RANDOM0,
  29164. 'a_Random1': VertexShuriKenParticle.PARTICLE_RANDOM1,
  29165. 'a_SimulationWorldPostion': VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION,
  29166. 'a_SimulationWorldRotation': VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION
  29167. };
  29168. uniformMap = {
  29169. 'u_Tintcolor': Shader3D.PERIOD_MATERIAL,
  29170. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29171. 'u_texture': Shader3D.PERIOD_MATERIAL,
  29172. 'u_WorldPosition': Shader3D.PERIOD_SPRITE,
  29173. 'u_WorldRotation': Shader3D.PERIOD_SPRITE,
  29174. 'u_PositionScale': Shader3D.PERIOD_SPRITE,
  29175. 'u_SizeScale': Shader3D.PERIOD_SPRITE,
  29176. 'u_ScalingMode': Shader3D.PERIOD_SPRITE,
  29177. 'u_Gravity': Shader3D.PERIOD_SPRITE,
  29178. 'u_ThreeDStartRotation': Shader3D.PERIOD_SPRITE,
  29179. 'u_StretchedBillboardLengthScale': Shader3D.PERIOD_SPRITE,
  29180. 'u_StretchedBillboardSpeedScale': Shader3D.PERIOD_SPRITE,
  29181. 'u_SimulationSpace': Shader3D.PERIOD_SPRITE,
  29182. 'u_CurrentTime': Shader3D.PERIOD_SPRITE,
  29183. 'u_ColorOverLifeGradientAlphas': Shader3D.PERIOD_SPRITE,
  29184. 'u_ColorOverLifeGradientColors': Shader3D.PERIOD_SPRITE,
  29185. 'u_MaxColorOverLifeGradientAlphas': Shader3D.PERIOD_SPRITE,
  29186. 'u_MaxColorOverLifeGradientColors': Shader3D.PERIOD_SPRITE,
  29187. 'u_VOLVelocityConst': Shader3D.PERIOD_SPRITE,
  29188. 'u_VOLVelocityGradientX': Shader3D.PERIOD_SPRITE,
  29189. 'u_VOLVelocityGradientY': Shader3D.PERIOD_SPRITE,
  29190. 'u_VOLVelocityGradientZ': Shader3D.PERIOD_SPRITE,
  29191. 'u_VOLVelocityConstMax': Shader3D.PERIOD_SPRITE,
  29192. 'u_VOLVelocityGradientMaxX': Shader3D.PERIOD_SPRITE,
  29193. 'u_VOLVelocityGradientMaxY': Shader3D.PERIOD_SPRITE,
  29194. 'u_VOLVelocityGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29195. 'u_VOLSpaceType': Shader3D.PERIOD_SPRITE,
  29196. 'u_SOLSizeGradient': Shader3D.PERIOD_SPRITE,
  29197. 'u_SOLSizeGradientX': Shader3D.PERIOD_SPRITE,
  29198. 'u_SOLSizeGradientY': Shader3D.PERIOD_SPRITE,
  29199. 'u_SOLSizeGradientZ': Shader3D.PERIOD_SPRITE,
  29200. 'u_SOLSizeGradientMax': Shader3D.PERIOD_SPRITE,
  29201. 'u_SOLSizeGradientMaxX': Shader3D.PERIOD_SPRITE,
  29202. 'u_SOLSizeGradientMaxY': Shader3D.PERIOD_SPRITE,
  29203. 'u_SOLSizeGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29204. 'u_ROLAngularVelocityConst': Shader3D.PERIOD_SPRITE,
  29205. 'u_ROLAngularVelocityConstSeprarate': Shader3D.PERIOD_SPRITE,
  29206. 'u_ROLAngularVelocityGradient': Shader3D.PERIOD_SPRITE,
  29207. 'u_ROLAngularVelocityGradientX': Shader3D.PERIOD_SPRITE,
  29208. 'u_ROLAngularVelocityGradientY': Shader3D.PERIOD_SPRITE,
  29209. 'u_ROLAngularVelocityGradientZ': Shader3D.PERIOD_SPRITE,
  29210. 'u_ROLAngularVelocityConstMax': Shader3D.PERIOD_SPRITE,
  29211. 'u_ROLAngularVelocityConstMaxSeprarate': Shader3D.PERIOD_SPRITE,
  29212. 'u_ROLAngularVelocityGradientMax': Shader3D.PERIOD_SPRITE,
  29213. 'u_ROLAngularVelocityGradientMaxX': Shader3D.PERIOD_SPRITE,
  29214. 'u_ROLAngularVelocityGradientMaxY': Shader3D.PERIOD_SPRITE,
  29215. 'u_ROLAngularVelocityGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29216. 'u_ROLAngularVelocityGradientMaxW': Shader3D.PERIOD_SPRITE,
  29217. 'u_TSACycles': Shader3D.PERIOD_SPRITE,
  29218. 'u_TSASubUVLength': Shader3D.PERIOD_SPRITE,
  29219. 'u_TSAGradientUVs': Shader3D.PERIOD_SPRITE,
  29220. 'u_TSAMaxGradientUVs': Shader3D.PERIOD_SPRITE,
  29221. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29222. 'u_CameraDirection': Shader3D.PERIOD_CAMERA,
  29223. 'u_CameraUp': Shader3D.PERIOD_CAMERA,
  29224. 'u_View': Shader3D.PERIOD_CAMERA,
  29225. 'u_Projection': Shader3D.PERIOD_CAMERA,
  29226. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29227. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29228. 'u_FogColor': Shader3D.PERIOD_SCENE
  29229. };
  29230. stateMap = {
  29231. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29232. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29233. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29234. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29235. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29236. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29237. };
  29238. shader = Shader3D.add("PARTICLESHURIKEN");
  29239. subShader = new SubShader(attributeMap, uniformMap);
  29240. shader.addSubShader(subShader);
  29241. subShader.addShaderPass(ParticleShuriKenVS, ParticleShuriKenPS, stateMap);
  29242. attributeMap = {
  29243. 'a_Position': VertexMesh.MESH_POSITION0
  29244. };
  29245. uniformMap = {
  29246. 'u_TintColor': Shader3D.PERIOD_MATERIAL,
  29247. 'u_Exposure': Shader3D.PERIOD_MATERIAL,
  29248. 'u_Rotation': Shader3D.PERIOD_MATERIAL,
  29249. 'u_CubeTexture': Shader3D.PERIOD_MATERIAL,
  29250. 'u_ViewProjection': Shader3D.PERIOD_CAMERA
  29251. };
  29252. shader = Shader3D.add("SkyBox");
  29253. subShader = new SubShader(attributeMap, uniformMap);
  29254. shader.addSubShader(subShader);
  29255. subShader.addShaderPass(SkyBoxVS, SkyBoxPS);
  29256. attributeMap = {
  29257. 'a_Position': VertexMesh.MESH_POSITION0
  29258. };
  29259. uniformMap = {
  29260. 'u_SunSize': Shader3D.PERIOD_MATERIAL,
  29261. 'u_SunSizeConvergence': Shader3D.PERIOD_MATERIAL,
  29262. 'u_AtmosphereThickness': Shader3D.PERIOD_MATERIAL,
  29263. 'u_SkyTint': Shader3D.PERIOD_MATERIAL,
  29264. 'u_GroundTint': Shader3D.PERIOD_MATERIAL,
  29265. 'u_Exposure': Shader3D.PERIOD_MATERIAL,
  29266. 'u_ViewProjection': Shader3D.PERIOD_CAMERA,
  29267. 'u_SunLight.direction': Shader3D.PERIOD_SCENE,
  29268. 'u_SunLight.color': Shader3D.PERIOD_SCENE,
  29269. };
  29270. shader = Shader3D.add("SkyBoxProcedural");
  29271. subShader = new SubShader(attributeMap, uniformMap);
  29272. shader.addSubShader(subShader);
  29273. subShader.addShaderPass(SkyBoxProceduralVS, SkyBoxProceduralPS);
  29274. attributeMap = {
  29275. 'a_Position': VertexMesh.MESH_POSITION0,
  29276. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29277. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0
  29278. };
  29279. uniformMap = {
  29280. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29281. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29282. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29283. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  29284. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  29285. 'u_SplatAlphaTexture': Shader3D.PERIOD_MATERIAL,
  29286. 'u_DiffuseTexture1': Shader3D.PERIOD_MATERIAL,
  29287. 'u_DiffuseTexture2': Shader3D.PERIOD_MATERIAL,
  29288. 'u_DiffuseTexture3': Shader3D.PERIOD_MATERIAL,
  29289. 'u_DiffuseTexture4': Shader3D.PERIOD_MATERIAL,
  29290. 'u_DiffuseTexture5': Shader3D.PERIOD_MATERIAL,
  29291. 'u_DiffuseScaleOffset1': Shader3D.PERIOD_MATERIAL,
  29292. 'u_DiffuseScaleOffset2': Shader3D.PERIOD_MATERIAL,
  29293. 'u_DiffuseScaleOffset3': Shader3D.PERIOD_MATERIAL,
  29294. 'u_DiffuseScaleOffset4': Shader3D.PERIOD_MATERIAL,
  29295. 'u_DiffuseScaleOffset5': Shader3D.PERIOD_MATERIAL,
  29296. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29297. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29298. 'u_FogColor': Shader3D.PERIOD_SCENE,
  29299. 'u_DirectionLight.Direction': Shader3D.PERIOD_SCENE,
  29300. 'u_DirectionLight.Color': Shader3D.PERIOD_SCENE,
  29301. 'u_PointLight.Position': Shader3D.PERIOD_SCENE,
  29302. 'u_PointLight.Range': Shader3D.PERIOD_SCENE,
  29303. 'u_PointLight.Attenuation': Shader3D.PERIOD_SCENE,
  29304. 'u_PointLight.Color': Shader3D.PERIOD_SCENE,
  29305. 'u_SpotLight.Position': Shader3D.PERIOD_SCENE,
  29306. 'u_SpotLight.Direction': Shader3D.PERIOD_SCENE,
  29307. 'u_SpotLight.Range': Shader3D.PERIOD_SCENE,
  29308. 'u_SpotLight.Spot': Shader3D.PERIOD_SCENE,
  29309. 'u_SpotLight.Color': Shader3D.PERIOD_SCENE,
  29310. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  29311. 'u_shadowMap1': Shader3D.PERIOD_SCENE,
  29312. 'u_shadowMap2': Shader3D.PERIOD_SCENE,
  29313. 'u_shadowMap3': Shader3D.PERIOD_SCENE,
  29314. 'u_shadowPSSMDistance': Shader3D.PERIOD_SCENE,
  29315. 'u_lightShadowVP': Shader3D.PERIOD_SCENE,
  29316. 'u_shadowPCFoffset': Shader3D.PERIOD_SCENE
  29317. };
  29318. stateMap = {
  29319. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29320. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29321. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29322. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29323. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29324. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29325. };
  29326. shader = Shader3D.add("ExtendTerrain");
  29327. subShader = new SubShader(attributeMap, uniformMap);
  29328. shader.addSubShader(subShader);
  29329. subShader.addShaderPass(extendTerrainVS, extendTerrainPS, stateMap);
  29330. attributeMap = {
  29331. 'a_Position': VertexTrail.TRAIL_POSITION0,
  29332. 'a_OffsetVector': VertexTrail.TRAIL_OFFSETVECTOR,
  29333. 'a_Texcoord0X': VertexTrail.TRAIL_TEXTURECOORDINATE0X,
  29334. 'a_Texcoord0Y': VertexTrail.TRAIL_TEXTURECOORDINATE0Y,
  29335. 'a_BirthTime': VertexTrail.TRAIL_TIME0,
  29336. 'a_Color': VertexTrail.TRAIL_COLOR
  29337. };
  29338. uniformMap = {
  29339. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29340. 'u_View': Shader3D.PERIOD_CAMERA,
  29341. 'u_Projection': Shader3D.PERIOD_CAMERA,
  29342. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29343. 'u_MainTexture': Shader3D.PERIOD_MATERIAL,
  29344. 'u_MainColor': Shader3D.PERIOD_MATERIAL,
  29345. 'u_CurTime': Shader3D.PERIOD_SPRITE,
  29346. 'u_LifeTime': Shader3D.PERIOD_SPRITE,
  29347. 'u_WidthCurve': Shader3D.PERIOD_SPRITE,
  29348. 'u_WidthCurveKeyLength': Shader3D.PERIOD_SPRITE,
  29349. 'u_GradientColorkey': Shader3D.PERIOD_SPRITE,
  29350. 'u_GradientAlphakey': Shader3D.PERIOD_SPRITE
  29351. };
  29352. stateMap = {
  29353. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29354. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29355. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29356. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29357. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29358. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29359. };
  29360. shader = Shader3D.add("Trail");
  29361. subShader = new SubShader(attributeMap, uniformMap);
  29362. shader.addSubShader(subShader);
  29363. subShader.addShaderPass(TrailVS, TrailPS, stateMap);
  29364. attributeMap = {
  29365. 'a_Position': VertexMesh.MESH_POSITION0,
  29366. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29367. 'a_Tangent0': VertexMesh.MESH_TANGENT0
  29368. };
  29369. uniformMap = {
  29370. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29371. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29372. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29373. 'u_Time': Shader3D.PERIOD_SCENE,
  29374. 'u_MainTexture': Shader3D.PERIOD_MATERIAL,
  29375. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  29376. 'u_HorizonColor': Shader3D.PERIOD_MATERIAL,
  29377. 'u_WaveScale': Shader3D.PERIOD_MATERIAL,
  29378. 'u_WaveSpeed': Shader3D.PERIOD_MATERIAL
  29379. };
  29380. shader = Shader3D.add("WaterPrimary");
  29381. subShader = new SubShader(attributeMap, uniformMap);
  29382. shader.addSubShader(subShader);
  29383. subShader.addShaderPass(WaterPrimaryVS, WaterPrimaryPS);
  29384. attributeMap = {
  29385. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  29386. };
  29387. uniformMap = {
  29388. 'u_MainTex': Shader3D.PERIOD_MATERIAL
  29389. };
  29390. shader = Shader3D.add("BlitScreen");
  29391. subShader = new SubShader(attributeMap, uniformMap);
  29392. shader.addSubShader(subShader);
  29393. var shaderPass = subShader.addShaderPass(BlitScreenVS, BlitScreenPS);
  29394. var renderState = shaderPass.renderState;
  29395. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29396. renderState.depthWrite = false;
  29397. renderState.cull = RenderState.CULL_NONE;
  29398. renderState.blend = RenderState.BLEND_DISABLE;
  29399. attributeMap = {
  29400. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  29401. };
  29402. uniformMap = {
  29403. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  29404. 'u_BloomTex': Shader3D.PERIOD_MATERIAL,
  29405. 'u_AutoExposureTex': Shader3D.PERIOD_MATERIAL,
  29406. 'u_MainTex_TexelSize': Shader3D.PERIOD_MATERIAL,
  29407. 'u_SampleScale': Shader3D.PERIOD_MATERIAL,
  29408. 'u_Threshold': Shader3D.PERIOD_MATERIAL,
  29409. 'u_Params': Shader3D.PERIOD_MATERIAL
  29410. };
  29411. shader = Shader3D.add("PostProcessBloom");
  29412. subShader = new SubShader(attributeMap, uniformMap);
  29413. shader.addSubShader(subShader);
  29414. shaderPass = subShader.addShaderPass(BloomVS, BloomPrefilter13PS);
  29415. renderState = shaderPass.renderState;
  29416. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29417. renderState.depthWrite = false;
  29418. renderState.cull = RenderState.CULL_NONE;
  29419. renderState.blend = RenderState.BLEND_DISABLE;
  29420. subShader = new SubShader(attributeMap, uniformMap);
  29421. shader.addSubShader(subShader);
  29422. shaderPass = subShader.addShaderPass(BloomVS, BloomPrefilter4PS);
  29423. renderState = shaderPass.renderState;
  29424. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29425. renderState.depthWrite = false;
  29426. renderState.cull = RenderState.CULL_NONE;
  29427. renderState.blend = RenderState.BLEND_DISABLE;
  29428. subShader = new SubShader(attributeMap, uniformMap);
  29429. shader.addSubShader(subShader);
  29430. shaderPass = subShader.addShaderPass(BloomVS, BloomDownsample13PS);
  29431. renderState = shaderPass.renderState;
  29432. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29433. renderState.depthWrite = false;
  29434. renderState.cull = RenderState.CULL_NONE;
  29435. renderState.blend = RenderState.BLEND_DISABLE;
  29436. subShader = new SubShader(attributeMap, uniformMap);
  29437. shader.addSubShader(subShader);
  29438. shaderPass = subShader.addShaderPass(BloomVS, BloomDownsample4PS);
  29439. renderState = shaderPass.renderState;
  29440. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29441. renderState.depthWrite = false;
  29442. renderState.cull = RenderState.CULL_NONE;
  29443. renderState.blend = RenderState.BLEND_DISABLE;
  29444. subShader = new SubShader(attributeMap, uniformMap);
  29445. shader.addSubShader(subShader);
  29446. shaderPass = subShader.addShaderPass(BloomVS, BloomUpsampleTentPS);
  29447. renderState = shaderPass.renderState;
  29448. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29449. renderState.depthWrite = false;
  29450. renderState.cull = RenderState.CULL_NONE;
  29451. renderState.blend = RenderState.BLEND_DISABLE;
  29452. subShader = new SubShader(attributeMap, uniformMap);
  29453. shader.addSubShader(subShader);
  29454. shaderPass = subShader.addShaderPass(BloomVS, BloomUpsampleBoxPS);
  29455. renderState = shaderPass.renderState;
  29456. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29457. renderState.depthWrite = false;
  29458. renderState.cull = RenderState.CULL_NONE;
  29459. renderState.blend = RenderState.BLEND_DISABLE;
  29460. attributeMap = {
  29461. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  29462. };
  29463. uniformMap = {
  29464. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  29465. 'u_BloomTex': Shader3D.PERIOD_MATERIAL,
  29466. 'u_AutoExposureTex': Shader3D.PERIOD_MATERIAL,
  29467. 'u_Bloom_DirtTileOffset': Shader3D.PERIOD_MATERIAL,
  29468. 'u_Bloom_DirtTex': Shader3D.PERIOD_MATERIAL,
  29469. 'u_BloomTex_TexelSize': Shader3D.PERIOD_MATERIAL,
  29470. 'u_Bloom_Settings': Shader3D.PERIOD_MATERIAL,
  29471. 'u_Bloom_Color': Shader3D.PERIOD_MATERIAL
  29472. };
  29473. shader = Shader3D.add("PostProcessComposite");
  29474. subShader = new SubShader(attributeMap, uniformMap);
  29475. shader.addSubShader(subShader);
  29476. shaderPass = subShader.addShaderPass(CompositeVS, CompositePS);
  29477. renderState = shaderPass.renderState;
  29478. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29479. renderState.depthWrite = false;
  29480. renderState.cull = RenderState.CULL_NONE;
  29481. renderState.blend = RenderState.BLEND_DISABLE;
  29482. }
  29483. }
  29484. class ParallelSplitShadowMap {
  29485. constructor() {
  29486. this._spiltDistance = [];
  29487. this._currentPSSM = -1;
  29488. this._shadowMapCount = 3;
  29489. this._maxDistance = 200.0;
  29490. this._ratioOfDistance = 1.0 / this._shadowMapCount;
  29491. this._globalParallelLightDir = new Vector3(0, -1, 0);
  29492. this._statesDirty = true;
  29493. this._shadowMapTextureSize = 1024;
  29494. this._scene = null;
  29495. this._boundingSphere = new Array(ParallelSplitShadowMap.MAX_PSSM_COUNT + 1);
  29496. this._boundingBox = new Array(ParallelSplitShadowMap.MAX_PSSM_COUNT + 1);
  29497. this._frustumPos = new Array((ParallelSplitShadowMap.MAX_PSSM_COUNT + 1) * 4);
  29498. this._uniformDistance = new Array(ParallelSplitShadowMap.MAX_PSSM_COUNT + 1);
  29499. this._logDistance = new Array(ParallelSplitShadowMap.MAX_PSSM_COUNT + 1);
  29500. this._dimension = new Array(ParallelSplitShadowMap.MAX_PSSM_COUNT + 1);
  29501. this._PCFType = 0;
  29502. this._tempLookAt3 = new Vector3();
  29503. this._tempLookAt4 = new Vector4();
  29504. this._tempValue = new Vector4();
  29505. this._tempPos = new Vector3();
  29506. this._tempLightUp = new Vector3();
  29507. this._tempMin = new Vector4();
  29508. this._tempMax = new Vector4();
  29509. this._tempMatrix44 = new Matrix4x4;
  29510. this._splitFrustumCulling = new BoundFrustum(Matrix4x4.DEFAULT);
  29511. this._tempScaleMatrix44 = new Matrix4x4();
  29512. this._shadowPCFOffset = new Vector2(1.0 / 1024.0, 1.0 / 1024.0);
  29513. this._shaderValueDistance = new Vector4();
  29514. this._shaderValueLightVP = null;
  29515. this.cameras = [];
  29516. this._shaderValueVPs = [];
  29517. var i;
  29518. for (i = 0; i < this._spiltDistance.length; i++) {
  29519. this._spiltDistance[i] = 0.0;
  29520. }
  29521. for (i = 0; i < this._dimension.length; i++) {
  29522. this._dimension[i] = new Vector2();
  29523. }
  29524. for (i = 0; i < this._frustumPos.length; i++) {
  29525. this._frustumPos[i] = new Vector3();
  29526. }
  29527. for (i = 0; i < this._boundingBox.length; i++) {
  29528. this._boundingBox[i] = new BoundBox(new Vector3(), new Vector3());
  29529. }
  29530. for (i = 0; i < this._boundingSphere.length; i++) {
  29531. this._boundingSphere[i] = new BoundSphere(new Vector3(), 0.0);
  29532. }
  29533. Matrix4x4.createScaling(new Vector3(0.5, 0.5, 1.0), this._tempScaleMatrix44);
  29534. this._tempScaleMatrix44.elements[12] = 0.5;
  29535. this._tempScaleMatrix44.elements[13] = 0.5;
  29536. }
  29537. setInfo(scene, maxDistance, globalParallelDir, shadowMapTextureSize, numberOfPSSM, PCFType) {
  29538. if (numberOfPSSM > ParallelSplitShadowMap.MAX_PSSM_COUNT) {
  29539. this._shadowMapCount = ParallelSplitShadowMap.MAX_PSSM_COUNT;
  29540. }
  29541. this._scene = scene;
  29542. this._maxDistance = maxDistance;
  29543. this.shadowMapCount = numberOfPSSM;
  29544. this._globalParallelLightDir = globalParallelDir;
  29545. this._ratioOfDistance = 1.0 / this._shadowMapCount;
  29546. for (var i = 0; i < this._spiltDistance.length; i++) {
  29547. this._spiltDistance[i] = 0.0;
  29548. }
  29549. this._shadowMapTextureSize = shadowMapTextureSize;
  29550. this._shadowPCFOffset.x = 1.0 / this._shadowMapTextureSize;
  29551. this._shadowPCFOffset.y = 1.0 / this._shadowMapTextureSize;
  29552. this.setPCFType(PCFType);
  29553. this._statesDirty = true;
  29554. }
  29555. setPCFType(PCFtype) {
  29556. this._PCFType = PCFtype;
  29557. var defineData = this._scene._shaderValues;
  29558. switch (this._PCFType) {
  29559. case 0:
  29560. defineData.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF_NO);
  29561. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF1);
  29562. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF2);
  29563. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF3);
  29564. break;
  29565. case 1:
  29566. defineData.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF1);
  29567. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF_NO);
  29568. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF2);
  29569. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF3);
  29570. break;
  29571. case 2:
  29572. defineData.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF2);
  29573. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF_NO);
  29574. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF1);
  29575. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF3);
  29576. break;
  29577. case 3:
  29578. defineData.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF3);
  29579. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF_NO);
  29580. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF1);
  29581. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF2);
  29582. break;
  29583. }
  29584. }
  29585. getPCFType() {
  29586. return this._PCFType;
  29587. }
  29588. setFarDistance(value) {
  29589. if (this._maxDistance != value) {
  29590. this._maxDistance = value;
  29591. this._statesDirty = true;
  29592. }
  29593. }
  29594. getFarDistance() {
  29595. return this._maxDistance;
  29596. }
  29597. set shadowMapCount(value) {
  29598. value = value > 0 ? value : 1;
  29599. value = value <= ParallelSplitShadowMap.MAX_PSSM_COUNT ? value : ParallelSplitShadowMap.MAX_PSSM_COUNT;
  29600. if (this._shadowMapCount != value) {
  29601. this._shadowMapCount = value;
  29602. this._ratioOfDistance = 1.0 / this._shadowMapCount;
  29603. this._statesDirty = true;
  29604. this._shaderValueLightVP = new Float32Array(value * 16);
  29605. this._shaderValueVPs.length = value;
  29606. for (var i = 0; i < value; i++)
  29607. this._shaderValueVPs[i] = new Float32Array(this._shaderValueLightVP.buffer, i * 64);
  29608. }
  29609. }
  29610. get shadowMapCount() {
  29611. return this._shadowMapCount;
  29612. }
  29613. _beginSampler(index, sceneCamera) {
  29614. if (index < 0 || index > this._shadowMapCount)
  29615. throw new Error("ParallelSplitShadowMap: beginSample invalid index");
  29616. this._currentPSSM = index;
  29617. this._update(sceneCamera);
  29618. }
  29619. endSampler(sceneCamera) {
  29620. this._currentPSSM = -1;
  29621. }
  29622. _calcAllLightCameraInfo(sceneCamera) {
  29623. if (this._shadowMapCount === 1) {
  29624. this._beginSampler(0, sceneCamera);
  29625. this.endSampler(sceneCamera);
  29626. }
  29627. else {
  29628. for (var i = 0, n = this._shadowMapCount + 1; i < n; i++) {
  29629. this._beginSampler(i, sceneCamera);
  29630. this.endSampler(sceneCamera);
  29631. }
  29632. }
  29633. }
  29634. _recalculate(nearPlane, fieldOfView, aspectRatio) {
  29635. this._calcSplitDistance(nearPlane);
  29636. this._calcBoundingBox(fieldOfView, aspectRatio);
  29637. this._rebuildRenderInfo();
  29638. }
  29639. _update(sceneCamera) {
  29640. var nearPlane = sceneCamera.nearPlane;
  29641. var fieldOfView = sceneCamera.fieldOfView;
  29642. var aspectRatio = sceneCamera.aspectRatio;
  29643. if (this._statesDirty || this.lastNearPlane !== nearPlane || this.lastFieldOfView !== fieldOfView || this.lastAspectRatio !== aspectRatio) {
  29644. this._recalculate(nearPlane, fieldOfView, aspectRatio);
  29645. this._uploadShaderValue();
  29646. this._statesDirty = false;
  29647. this.lastNearPlane = nearPlane;
  29648. this.lastFieldOfView = fieldOfView;
  29649. this.lastAspectRatio = aspectRatio;
  29650. }
  29651. this._calcLightViewProject(sceneCamera);
  29652. }
  29653. _uploadShaderValue() {
  29654. var sceneSV = this._scene._shaderValues;
  29655. switch (this._shadowMapCount) {
  29656. case 1:
  29657. sceneSV.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM1);
  29658. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM2);
  29659. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM3);
  29660. break;
  29661. case 2:
  29662. sceneSV.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM2);
  29663. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM1);
  29664. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM3);
  29665. break;
  29666. case 3:
  29667. sceneSV.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM3);
  29668. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM1);
  29669. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM2);
  29670. break;
  29671. }
  29672. sceneSV.setVector(ILaya3D.Scene3D.SHADOWDISTANCE, this._shaderValueDistance);
  29673. sceneSV.setBuffer(ILaya3D.Scene3D.SHADOWLIGHTVIEWPROJECT, this._shaderValueLightVP);
  29674. sceneSV.setVector2(ILaya3D.Scene3D.SHADOWMAPPCFOFFSET, this._shadowPCFOffset);
  29675. switch (this._shadowMapCount) {
  29676. case 3:
  29677. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE1, this.cameras[1].renderTarget);
  29678. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE2, this.cameras[2].renderTarget);
  29679. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE3, this.cameras[3].renderTarget);
  29680. break;
  29681. case 2:
  29682. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE1, this.cameras[1].renderTarget);
  29683. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE2, this.cameras[2].renderTarget);
  29684. break;
  29685. case 1:
  29686. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE1, this.cameras[1].renderTarget);
  29687. break;
  29688. }
  29689. }
  29690. _calcSplitDistance(nearPlane) {
  29691. var far = this._maxDistance;
  29692. var invNumberOfPSSM = 1.0 / this._shadowMapCount;
  29693. var i;
  29694. for (i = 0; i <= this._shadowMapCount; i++) {
  29695. this._uniformDistance[i] = nearPlane + (far - nearPlane) * i * invNumberOfPSSM;
  29696. }
  29697. var farDivNear = far / nearPlane;
  29698. for (i = 0; i <= this._shadowMapCount; i++) {
  29699. var n = Math.pow(farDivNear, i * invNumberOfPSSM);
  29700. this._logDistance[i] = nearPlane * n;
  29701. }
  29702. for (i = 0; i <= this._shadowMapCount; i++) {
  29703. this._spiltDistance[i] = this._uniformDistance[i] * this._ratioOfDistance + this._logDistance[i] * (1.0 - this._ratioOfDistance);
  29704. }
  29705. this._shaderValueDistance.x = (this._spiltDistance[1] != undefined) && (this._spiltDistance[1]);
  29706. this._shaderValueDistance.y = (this._spiltDistance[2] != undefined) && (this._spiltDistance[2]);
  29707. this._shaderValueDistance.z = (this._spiltDistance[3] != undefined) && (this._spiltDistance[3]);
  29708. this._shaderValueDistance.w = (this._spiltDistance[4] != undefined) && (this._spiltDistance[4]);
  29709. }
  29710. _calcBoundingBox(fieldOfView, aspectRatio) {
  29711. var fov = 3.1415926 * fieldOfView / 180.0;
  29712. var halfTanValue = Math.tan(fov / 2.0);
  29713. var height;
  29714. var width;
  29715. var distance;
  29716. var i;
  29717. for (i = 0; i <= this._shadowMapCount; i++) {
  29718. distance = this._spiltDistance[i];
  29719. height = distance * halfTanValue;
  29720. width = height * aspectRatio;
  29721. var temp = this._frustumPos[i * 4 + 0];
  29722. temp.x = -width;
  29723. temp.y = -height;
  29724. temp.z = -distance;
  29725. temp = this._frustumPos[i * 4 + 1];
  29726. temp.x = width;
  29727. temp.y = -height;
  29728. temp.z = -distance;
  29729. temp = this._frustumPos[i * 4 + 2];
  29730. temp.x = -width;
  29731. temp.y = height;
  29732. temp.z = -distance;
  29733. temp = this._frustumPos[i * 4 + 3];
  29734. temp.x = width;
  29735. temp.y = height;
  29736. temp.z = -distance;
  29737. temp = this._dimension[i];
  29738. temp.x = width;
  29739. temp.y = height;
  29740. }
  29741. var d;
  29742. var min;
  29743. var max;
  29744. var center;
  29745. for (i = 1; i <= this._shadowMapCount; i++) {
  29746. d = this._dimension[i];
  29747. min = this._boundingBox[i].min;
  29748. min.x = -d.x;
  29749. min.y = -d.y;
  29750. min.z = -this._spiltDistance[i];
  29751. max = this._boundingBox[i].max;
  29752. max.x = d.x;
  29753. max.y = d.y;
  29754. max.z = -this._spiltDistance[i - 1];
  29755. center = this._boundingSphere[i].center;
  29756. center.x = (min.x + max.x) * 0.5;
  29757. center.y = (min.y + max.y) * 0.5;
  29758. center.z = (min.z + max.z) * 0.5;
  29759. this._boundingSphere[i].radius = Math.sqrt(Math.pow(max.x - min.x, 2) + Math.pow(max.y - min.y, 2) + Math.pow(max.z - min.z, 2)) * 0.5;
  29760. }
  29761. min = this._boundingBox[0].min;
  29762. d = this._dimension[this._shadowMapCount];
  29763. min.x = -d.x;
  29764. min.y = -d.y;
  29765. min.z = -this._spiltDistance[this._shadowMapCount];
  29766. max = this._boundingBox[0].max;
  29767. max.x = d.x;
  29768. max.y = d.y;
  29769. max.z = -this._spiltDistance[0];
  29770. center = this._boundingSphere[0].center;
  29771. center.x = (min.x + max.x) * 0.5;
  29772. center.y = (min.y + max.y) * 0.5;
  29773. center.z = (min.z + max.z) * 0.5;
  29774. this._boundingSphere[0].radius = Math.sqrt(Math.pow(max.x - min.x, 2) + Math.pow(max.y - min.y, 2) + Math.pow(max.z - min.z, 2)) * 0.5;
  29775. }
  29776. calcSplitFrustum(sceneCamera) {
  29777. if (this._currentPSSM > 0) {
  29778. Matrix4x4.createPerspective(3.1416 * sceneCamera.fieldOfView / 180.0, sceneCamera.aspectRatio, this._spiltDistance[this._currentPSSM - 1], this._spiltDistance[this._currentPSSM], this._tempMatrix44);
  29779. }
  29780. else {
  29781. Matrix4x4.createPerspective(3.1416 * sceneCamera.fieldOfView / 180.0, sceneCamera.aspectRatio, this._spiltDistance[0], this._spiltDistance[this._shadowMapCount], this._tempMatrix44);
  29782. }
  29783. Matrix4x4.multiply(this._tempMatrix44, sceneCamera.viewMatrix, this._tempMatrix44);
  29784. this._splitFrustumCulling.matrix = this._tempMatrix44;
  29785. }
  29786. _rebuildRenderInfo() {
  29787. var nNum = this._shadowMapCount + 1;
  29788. var i;
  29789. this.cameras.length = nNum;
  29790. for (i = 0; i < nNum; i++) {
  29791. if (!this.cameras[i]) {
  29792. var camera = new Camera();
  29793. camera.name = "lightCamera" + i;
  29794. camera.clearColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  29795. this.cameras[i] = camera;
  29796. }
  29797. var shadowMap = this.cameras[i].renderTarget;
  29798. if (shadowMap == null || shadowMap.width != this._shadowMapTextureSize || shadowMap.height != this._shadowMapTextureSize) {
  29799. (shadowMap) && (shadowMap.destroy());
  29800. shadowMap = new RenderTexture(this._shadowMapTextureSize, this._shadowMapTextureSize, Laya.RenderTextureFormat.R8G8B8A8, Laya.RenderTextureDepthFormat.DEPTH_16);
  29801. shadowMap.filterMode = Laya.BaseTexture.FILTERMODE_POINT;
  29802. this.cameras[i].renderTarget = shadowMap;
  29803. }
  29804. }
  29805. }
  29806. _calcLightViewProject(sceneCamera) {
  29807. var boundSphere = this._boundingSphere[this._currentPSSM];
  29808. var cameraMatViewInv = sceneCamera.transform.worldMatrix;
  29809. var radius = boundSphere.radius;
  29810. boundSphere.center.cloneTo(this._tempLookAt3);
  29811. Vector3.transformV3ToV4(this._tempLookAt3, cameraMatViewInv, this._tempLookAt4);
  29812. var lookAt3Element = this._tempLookAt3;
  29813. var lookAt4Element = this._tempLookAt4;
  29814. lookAt3Element.x = lookAt4Element.x;
  29815. lookAt3Element.y = lookAt4Element.y;
  29816. lookAt3Element.z = lookAt4Element.z;
  29817. var lightUpElement = this._tempLightUp;
  29818. sceneCamera.transform.worldMatrix.getForward(ParallelSplitShadowMap._tempVector30);
  29819. var sceneCameraDir = ParallelSplitShadowMap._tempVector30;
  29820. lightUpElement.x = sceneCameraDir.x;
  29821. lightUpElement.y = 1.0;
  29822. lightUpElement.z = sceneCameraDir.z;
  29823. Vector3.normalize(this._tempLightUp, this._tempLightUp);
  29824. Vector3.scale(this._globalParallelLightDir, boundSphere.radius * 4, this._tempPos);
  29825. Vector3.subtract(this._tempLookAt3, this._tempPos, this._tempPos);
  29826. var curLightCamera = this.cameras[this._currentPSSM];
  29827. curLightCamera.transform.position = this._tempPos;
  29828. curLightCamera.transform.lookAt(this._tempLookAt3, this._tempLightUp, false);
  29829. var tempMax = this._tempMax;
  29830. var tempMin = this._tempMin;
  29831. tempMax.x = tempMax.y = tempMax.z = -100000.0;
  29832. tempMax.w = 1.0;
  29833. tempMin.x = tempMin.y = tempMin.z = 100000.0;
  29834. tempMin.w = 1.0;
  29835. Matrix4x4.multiply(curLightCamera.viewMatrix, cameraMatViewInv, this._tempMatrix44);
  29836. var tempValueElement = this._tempValue;
  29837. var corners = [];
  29838. corners.length = 8;
  29839. this._boundingBox[this._currentPSSM].getCorners(corners);
  29840. for (var i = 0; i < 8; i++) {
  29841. var frustumPosElements = corners[i];
  29842. tempValueElement.x = frustumPosElements.x;
  29843. tempValueElement.y = frustumPosElements.y;
  29844. tempValueElement.z = frustumPosElements.z;
  29845. tempValueElement.w = 1.0;
  29846. Vector4.transformByM4x4(this._tempValue, this._tempMatrix44, this._tempValue);
  29847. tempMin.x = (tempValueElement.x < tempMin.x) ? tempValueElement.x : tempMin.x;
  29848. tempMin.y = (tempValueElement.y < tempMin.y) ? tempValueElement.y : tempMin.y;
  29849. tempMin.z = (tempValueElement.z < tempMin.z) ? tempValueElement.z : tempMin.z;
  29850. tempMax.x = (tempValueElement.x > tempMax.x) ? tempValueElement.x : tempMax.x;
  29851. tempMax.y = (tempValueElement.y > tempMax.y) ? tempValueElement.y : tempMax.y;
  29852. tempMax.z = (tempValueElement.z > tempMax.z) ? tempValueElement.z : tempMax.z;
  29853. }
  29854. Vector4.add(this._tempMax, this._tempMin, this._tempValue);
  29855. tempValueElement.x *= 0.5;
  29856. tempValueElement.y *= 0.5;
  29857. tempValueElement.z *= 0.5;
  29858. tempValueElement.w = 1;
  29859. Vector4.transformByM4x4(this._tempValue, curLightCamera.transform.worldMatrix, this._tempValue);
  29860. var distance = Math.abs(-this._tempMax.z);
  29861. var farPlane = distance > this._maxDistance ? distance : this._maxDistance;
  29862. Vector3.scale(this._globalParallelLightDir, farPlane, this._tempPos);
  29863. var tempPosElement = this._tempPos;
  29864. tempPosElement.x = tempValueElement.x - tempPosElement.x;
  29865. tempPosElement.y = tempValueElement.y - tempPosElement.y;
  29866. tempPosElement.z = tempValueElement.z - tempPosElement.z;
  29867. curLightCamera.transform.position = this._tempPos;
  29868. curLightCamera.transform.lookAt(this._tempLookAt3, this._tempLightUp, false);
  29869. Matrix4x4.createOrthoOffCenter(tempMin.x, tempMax.x, tempMin.y, tempMax.y, 1.0, farPlane + 0.5 * (tempMax.z - tempMin.z), curLightCamera.projectionMatrix);
  29870. var projectView = curLightCamera.projectionViewMatrix;
  29871. ParallelSplitShadowMap.multiplyMatrixOutFloat32Array(this._tempScaleMatrix44, projectView, this._shaderValueVPs[this._currentPSSM]);
  29872. this._scene._shaderValues.setBuffer(ILaya3D.Scene3D.SHADOWLIGHTVIEWPROJECT, this._shaderValueLightVP);
  29873. }
  29874. static multiplyMatrixOutFloat32Array(left, right, out) {
  29875. var i, a, b, ai0, ai1, ai2, ai3;
  29876. a = left.elements;
  29877. b = right.elements;
  29878. for (i = 0; i < 4; i++) {
  29879. ai0 = a[i];
  29880. ai1 = a[i + 4];
  29881. ai2 = a[i + 8];
  29882. ai3 = a[i + 12];
  29883. out[i] = ai0 * b[0] + ai1 * b[1] + ai2 * b[2] + ai3 * b[3];
  29884. out[i + 4] = ai0 * b[4] + ai1 * b[5] + ai2 * b[6] + ai3 * b[7];
  29885. out[i + 8] = ai0 * b[8] + ai1 * b[9] + ai2 * b[10] + ai3 * b[11];
  29886. out[i + 12] = ai0 * b[12] + ai1 * b[13] + ai2 * b[14] + ai3 * b[15];
  29887. }
  29888. }
  29889. setShadowMapTextureSize(size) {
  29890. if (size !== this._shadowMapTextureSize) {
  29891. this._shadowMapTextureSize = size;
  29892. this._shadowPCFOffset.x = 1 / this._shadowMapTextureSize;
  29893. this._shadowPCFOffset.y = 1 / this._shadowMapTextureSize;
  29894. this._statesDirty = true;
  29895. }
  29896. }
  29897. disposeAllRenderTarget() {
  29898. for (var i = 0, n = this._shadowMapCount + 1; i < n; i++) {
  29899. if (this.cameras[i].renderTarget) {
  29900. this.cameras[i].renderTarget.destroy();
  29901. this.cameras[i].renderTarget = null;
  29902. }
  29903. }
  29904. }
  29905. }
  29906. ParallelSplitShadowMap.MAX_PSSM_COUNT = 3;
  29907. ParallelSplitShadowMap._tempVector30 = new Vector3();
  29908. class LightSprite extends Sprite3D {
  29909. constructor() {
  29910. super();
  29911. this._isAlternate = false;
  29912. this._intensity = 1.0;
  29913. this._intensityColor = new Vector3();
  29914. this.color = new Vector3(1.0, 1.0, 1.0);
  29915. this._shadow = false;
  29916. this._shadowFarPlane = 8;
  29917. this._shadowMapSize = 512;
  29918. this._shadowMapCount = 1;
  29919. this._shadowMapPCFType = 0;
  29920. this._lightmapBakedType = LightSprite.LIGHTMAPBAKEDTYPE_REALTIME;
  29921. }
  29922. get intensity() {
  29923. return this._intensity;
  29924. }
  29925. set intensity(value) {
  29926. this._intensity = value;
  29927. }
  29928. get shadow() {
  29929. return this._shadow;
  29930. }
  29931. set shadow(value) {
  29932. throw new Error("LightSprite: must override it.");
  29933. }
  29934. get shadowDistance() {
  29935. return this._shadowFarPlane;
  29936. }
  29937. set shadowDistance(value) {
  29938. this._shadowFarPlane = value;
  29939. (this._parallelSplitShadowMap) && (this._parallelSplitShadowMap.setFarDistance(value));
  29940. }
  29941. get shadowResolution() {
  29942. return this._shadowMapSize;
  29943. }
  29944. set shadowResolution(value) {
  29945. this._shadowMapSize = value;
  29946. (this._parallelSplitShadowMap) && (this._parallelSplitShadowMap.setShadowMapTextureSize(value));
  29947. }
  29948. get shadowPSSMCount() {
  29949. return this._shadowMapCount;
  29950. }
  29951. set shadowPSSMCount(value) {
  29952. this._shadowMapCount = value;
  29953. (this._parallelSplitShadowMap) && (this._parallelSplitShadowMap.shadowMapCount = value);
  29954. }
  29955. get shadowPCFType() {
  29956. return this._shadowMapPCFType;
  29957. }
  29958. set shadowPCFType(value) {
  29959. this._shadowMapPCFType = value;
  29960. (this._parallelSplitShadowMap) && (this._parallelSplitShadowMap.setPCFType(value));
  29961. }
  29962. get lightmapBakedType() {
  29963. return this._lightmapBakedType;
  29964. }
  29965. set lightmapBakedType(value) {
  29966. if (this._lightmapBakedType !== value) {
  29967. this._lightmapBakedType = value;
  29968. if (this.activeInHierarchy) {
  29969. if (value !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED)
  29970. this._addToScene();
  29971. else
  29972. this._removeFromScene();
  29973. }
  29974. }
  29975. }
  29976. _parse(data, spriteMap) {
  29977. super._parse(data, spriteMap);
  29978. var colorData = data.color;
  29979. this.color.fromArray(colorData);
  29980. this.intensity = data.intensity;
  29981. this.lightmapBakedType = data.lightmapBakedType;
  29982. }
  29983. _addToScene() {
  29984. var scene = this._scene;
  29985. var maxLightCount = Config3D._config.maxLightCount;
  29986. if (scene._lightCount < maxLightCount) {
  29987. scene._lightCount++;
  29988. this._addToLightQueue();
  29989. this._isAlternate = false;
  29990. }
  29991. else {
  29992. scene._alternateLights.add(this);
  29993. this._isAlternate = true;
  29994. console.warn("LightSprite:light count has large than maxLightCount,the latest added light will be ignore.");
  29995. }
  29996. }
  29997. _removeFromScene() {
  29998. var scene = this._scene;
  29999. if (this._isAlternate) {
  30000. scene._alternateLights.remove(this);
  30001. }
  30002. else {
  30003. scene._lightCount--;
  30004. this._removeFromLightQueue();
  30005. if (scene._alternateLights._length > 0) {
  30006. var alternateLight = scene._alternateLights.shift();
  30007. alternateLight._addToLightQueue();
  30008. alternateLight._isAlternate = false;
  30009. scene._lightCount++;
  30010. }
  30011. }
  30012. }
  30013. _addToLightQueue() {
  30014. }
  30015. _removeFromLightQueue() {
  30016. }
  30017. _onActive() {
  30018. super._onActive();
  30019. (this.lightmapBakedType !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED) && (this._addToScene());
  30020. }
  30021. _onInActive() {
  30022. super._onInActive();
  30023. (this.lightmapBakedType !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED) && (this._removeFromScene());
  30024. }
  30025. _create() {
  30026. return new LightSprite();
  30027. }
  30028. get diffuseColor() {
  30029. console.log("LightSprite: discard property,please use color property instead.");
  30030. return this.color;
  30031. }
  30032. set diffuseColor(value) {
  30033. console.log("LightSprite: discard property,please use color property instead.");
  30034. this.color = value;
  30035. }
  30036. }
  30037. LightSprite.LIGHTMAPBAKEDTYPE_REALTIME = 0;
  30038. LightSprite.LIGHTMAPBAKEDTYPE_MIXED = 1;
  30039. LightSprite.LIGHTMAPBAKEDTYPE_BAKED = 2;
  30040. class DirectionLight extends LightSprite {
  30041. set shadow(value) {
  30042. if (this._shadow !== value) {
  30043. this._shadow = value;
  30044. (this.scene) && (this._initShadow());
  30045. }
  30046. }
  30047. constructor() {
  30048. super();
  30049. this._direction = new Vector3();
  30050. }
  30051. _initShadow() {
  30052. if (this._shadow) {
  30053. this._parallelSplitShadowMap = new ParallelSplitShadowMap();
  30054. this.scene.parallelSplitShadowMaps.push(this._parallelSplitShadowMap);
  30055. this.transform.worldMatrix.getForward(this._direction);
  30056. Vector3.normalize(this._direction, this._direction);
  30057. this._parallelSplitShadowMap.setInfo(this.scene, this._shadowFarPlane, this._direction, this._shadowMapSize, this._shadowMapCount, this._shadowMapPCFType);
  30058. }
  30059. else {
  30060. var defineDatas = this._scene._shaderValues;
  30061. var parallelSplitShadowMaps = this.scene.parallelSplitShadowMaps;
  30062. parallelSplitShadowMaps.splice(parallelSplitShadowMaps.indexOf(this._parallelSplitShadowMap), 1);
  30063. this._parallelSplitShadowMap.disposeAllRenderTarget();
  30064. this._parallelSplitShadowMap = null;
  30065. defineDatas.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM1);
  30066. defineDatas.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM2);
  30067. defineDatas.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM3);
  30068. }
  30069. }
  30070. _addToLightQueue() {
  30071. this._scene._directionLights.add(this);
  30072. }
  30073. _removeFromLightQueue() {
  30074. this._scene._directionLights.remove(this);
  30075. }
  30076. }
  30077. class PointLight extends LightSprite {
  30078. get range() {
  30079. return this._range;
  30080. }
  30081. set range(value) {
  30082. this._range = value;
  30083. }
  30084. constructor() {
  30085. super();
  30086. this._range = 6.0;
  30087. }
  30088. _addToLightQueue() {
  30089. this._scene._pointLights.add(this);
  30090. }
  30091. _removeFromLightQueue() {
  30092. this._scene._pointLights.remove(this);
  30093. }
  30094. _parse(data, spriteMap) {
  30095. super._parse(data, spriteMap);
  30096. this.range = data.range;
  30097. }
  30098. }
  30099. class SpotLight extends LightSprite {
  30100. get spotAngle() {
  30101. return this._spotAngle;
  30102. }
  30103. set spotAngle(value) {
  30104. this._spotAngle = Math.max(Math.min(value, 179), 0);
  30105. }
  30106. get range() {
  30107. return this._range;
  30108. }
  30109. set range(value) {
  30110. this._range = value;
  30111. }
  30112. constructor() {
  30113. super();
  30114. this._spotAngle = 30.0;
  30115. this._range = 10.0;
  30116. this._direction = new Vector3();
  30117. }
  30118. _addToLightQueue() {
  30119. this._scene._spotLights.add(this);
  30120. }
  30121. _removeFromLightQueue() {
  30122. this._scene._spotLights.remove(this);
  30123. }
  30124. _parse(data, spriteMap) {
  30125. super._parse(data, spriteMap);
  30126. this.range = data.range;
  30127. this.spotAngle = data.spotAngle;
  30128. }
  30129. }
  30130. class Scene3DUtils {
  30131. static _createSprite3DInstance(nodeData, spriteMap, outBatchSprites) {
  30132. var node;
  30133. switch (nodeData.type) {
  30134. case "Scene3D":
  30135. node = new Scene3D();
  30136. break;
  30137. case "Sprite3D":
  30138. node = new Sprite3D();
  30139. break;
  30140. case "MeshSprite3D":
  30141. node = new MeshSprite3D();
  30142. (outBatchSprites && nodeData.props.isStatic) && (outBatchSprites.push(node));
  30143. break;
  30144. case "SkinnedMeshSprite3D":
  30145. node = new SkinnedMeshSprite3D();
  30146. break;
  30147. case "ShuriKenParticle3D":
  30148. node = new ShuriKenParticle3D();
  30149. break;
  30150. case "Camera":
  30151. node = new Camera();
  30152. break;
  30153. case "DirectionLight":
  30154. node = new DirectionLight();
  30155. break;
  30156. case "PointLight":
  30157. node = new PointLight();
  30158. break;
  30159. case "SpotLight":
  30160. node = new SpotLight();
  30161. break;
  30162. case "TrailSprite3D":
  30163. node = new TrailSprite3D();
  30164. break;
  30165. default:
  30166. throw new Error("Utils3D:unidentified class type in (.lh) file.");
  30167. }
  30168. var childData = nodeData.child;
  30169. if (childData) {
  30170. for (var i = 0, n = childData.length; i < n; i++) {
  30171. var child = Scene3DUtils._createSprite3DInstance(childData[i], spriteMap, outBatchSprites);
  30172. node.addChild(child);
  30173. }
  30174. }
  30175. spriteMap[nodeData.instanceID] = node;
  30176. return node;
  30177. }
  30178. static _createComponentInstance(nodeData, spriteMap) {
  30179. var node = spriteMap[nodeData.instanceID];
  30180. node._parse(nodeData.props, spriteMap);
  30181. var childData = nodeData.child;
  30182. if (childData) {
  30183. for (var i = 0, n = childData.length; i < n; i++)
  30184. Scene3DUtils._createComponentInstance(childData[i], spriteMap);
  30185. }
  30186. var componentsData = nodeData.components;
  30187. if (componentsData) {
  30188. for (var j = 0, m = componentsData.length; j < m; j++) {
  30189. var data = componentsData[j];
  30190. var clas = Laya.ClassUtils.getRegClass(data.type);
  30191. if (clas) {
  30192. var component = node.addComponent(clas);
  30193. component._parse(data);
  30194. }
  30195. else {
  30196. console.warn("Unkown component type.");
  30197. }
  30198. }
  30199. }
  30200. }
  30201. static _createNodeByJson02(nodeData, outBatchSprites) {
  30202. var spriteMap = {};
  30203. var node = Scene3DUtils._createSprite3DInstance(nodeData, spriteMap, outBatchSprites);
  30204. Scene3DUtils._createComponentInstance(nodeData, spriteMap);
  30205. return node;
  30206. }
  30207. static _parse(data, propertyParams = null, constructParams = null) {
  30208. var json = data.data;
  30209. var outBatchSprits = [];
  30210. var sprite;
  30211. switch (data.version) {
  30212. case "LAYAHIERARCHY:02":
  30213. sprite = Scene3DUtils._createNodeByJson02(json, outBatchSprits);
  30214. break;
  30215. default:
  30216. sprite = Scene3DUtils._createNodeByJson(json, outBatchSprits);
  30217. }
  30218. StaticBatchManager.combine(sprite, outBatchSprits);
  30219. return sprite;
  30220. }
  30221. static _parseScene(data, propertyParams = null, constructParams = null) {
  30222. var json = data.data;
  30223. var outBatchSprits = [];
  30224. var scene;
  30225. switch (data.version) {
  30226. case "LAYASCENE3D:02":
  30227. scene = Scene3DUtils._createNodeByJson02(json, outBatchSprits);
  30228. break;
  30229. default:
  30230. scene = Scene3DUtils._createNodeByJson(json, outBatchSprits);
  30231. }
  30232. StaticBatchManager.combine(null, outBatchSprits);
  30233. return scene;
  30234. }
  30235. static _createNodeByJson(nodeData, outBatchSprites) {
  30236. var node;
  30237. switch (nodeData.type) {
  30238. case "Scene3D":
  30239. node = new Scene3D();
  30240. break;
  30241. case "Sprite3D":
  30242. node = new Sprite3D();
  30243. break;
  30244. case "MeshSprite3D":
  30245. node = new MeshSprite3D();
  30246. (outBatchSprites && nodeData.props.isStatic) && (outBatchSprites.push(node));
  30247. break;
  30248. case "SkinnedMeshSprite3D":
  30249. node = new SkinnedMeshSprite3D();
  30250. break;
  30251. case "ShuriKenParticle3D":
  30252. node = new ShuriKenParticle3D();
  30253. break;
  30254. case "Camera":
  30255. node = new Camera();
  30256. break;
  30257. case "DirectionLight":
  30258. node = new DirectionLight();
  30259. break;
  30260. case "PointLight":
  30261. node = new PointLight();
  30262. break;
  30263. case "SpotLight":
  30264. node = new SpotLight();
  30265. break;
  30266. case "TrailSprite3D":
  30267. node = new TrailSprite3D();
  30268. break;
  30269. default:
  30270. throw new Error("Utils3D:unidentified class type in (.lh) file.");
  30271. }
  30272. var childData = nodeData.child;
  30273. if (childData) {
  30274. for (var i = 0, n = childData.length; i < n; i++) {
  30275. var child = Scene3DUtils._createNodeByJson(childData[i], outBatchSprites);
  30276. node.addChild(child);
  30277. }
  30278. }
  30279. var componentsData = nodeData.components;
  30280. if (componentsData) {
  30281. for (var j = 0, m = componentsData.length; j < m; j++) {
  30282. var data = componentsData[j];
  30283. var clas = Laya.ClassUtils.getRegClass(data.type);
  30284. if (clas) {
  30285. var component = node.addComponent(clas);
  30286. component._parse(data);
  30287. }
  30288. else {
  30289. console.warn("Unkown component type.");
  30290. }
  30291. }
  30292. }
  30293. node._parse(nodeData.props, null);
  30294. return node;
  30295. }
  30296. }
  30297. class Laya3D {
  30298. constructor() {
  30299. }
  30300. static get enbalePhysics() {
  30301. return Physics3D._enbalePhysics;
  30302. }
  30303. static _cancelLoadByUrl(url) {
  30304. Laya.Laya.loader.cancelLoadByUrl(url);
  30305. Laya3D._innerFirstLevelLoaderManager.cancelLoadByUrl(url);
  30306. Laya3D._innerSecondLevelLoaderManager.cancelLoadByUrl(url);
  30307. Laya3D._innerThirdLevelLoaderManager.cancelLoadByUrl(url);
  30308. Laya3D._innerFourthLevelLoaderManager.cancelLoadByUrl(url);
  30309. }
  30310. static _changeWebGLSize(width, height) {
  30311. Laya.WebGL.onStageResize(width, height);
  30312. RenderContext3D.clientWidth = width;
  30313. RenderContext3D.clientHeight = height;
  30314. }
  30315. static __init__(width, height, config) {
  30316. Laya.Config.isAntialias = config.isAntialias;
  30317. Laya.Config.isAlpha = config.isAlpha;
  30318. Laya.Config.premultipliedAlpha = config.premultipliedAlpha;
  30319. Laya.Config.isStencil = config.isStencil;
  30320. if (!Laya.WebGL.enable()) {
  30321. alert("Laya3D init error,must support webGL!");
  30322. return;
  30323. }
  30324. Laya.RunDriver.changeWebGLSize = Laya3D._changeWebGLSize;
  30325. Laya.Render.is3DMode = true;
  30326. Laya.Laya.init(width, height);
  30327. if (!Laya.Render.supportWebGLPlusRendering) {
  30328. Laya.LayaGL.instance = Laya.WebGLContext.mainContext;
  30329. Laya.LayaGL.instance.createCommandEncoder = function (reserveSize = 128, adjustSize = 64, isSyncToRenderThread = false) {
  30330. return new Laya.CommandEncoder(this, reserveSize, adjustSize, isSyncToRenderThread);
  30331. };
  30332. }
  30333. config._multiLighting = config.enbaleMultiLight && SystemUtils.supportTextureFormat(Laya.TextureFormat.R32G32B32A32);
  30334. ILaya3D.Scene3D = Scene3D;
  30335. ILaya3D.MeshRenderStaticBatchManager = MeshRenderStaticBatchManager;
  30336. ILaya3D.MeshRenderDynamicBatchManager = MeshRenderDynamicBatchManager;
  30337. ILaya3D.SubMeshDynamicBatch = SubMeshDynamicBatch;
  30338. ILaya3D.Laya3D = Laya3D;
  30339. ILaya3D.Matrix4x4 = Matrix4x4;
  30340. Laya3D.enableNative3D();
  30341. VertexElementFormat.__init__();
  30342. VertexMesh.__init__();
  30343. VertexShurikenParticleBillboard.__init__();
  30344. VertexShurikenParticleMesh.__init__();
  30345. VertexPositionTexture0.__init__();
  30346. VertexTrail.__init__();
  30347. VertexPositionTerrain.__init__();
  30348. PixelLineVertex.__init__();
  30349. SubMeshInstanceBatch.__init__();
  30350. SubMeshDynamicBatch.__init__();
  30351. Physics3D._physics3D = window.Physics3D;
  30352. if (Physics3D._physics3D) {
  30353. StaticPlaneColliderShape.__init__();
  30354. ColliderShape.__init__();
  30355. CompoundColliderShape.__init__();
  30356. PhysicsComponent.__init__();
  30357. PhysicsSimulation.__init__();
  30358. BoxColliderShape.__init__();
  30359. CylinderColliderShape.__init__();
  30360. CharacterController.__init__();
  30361. Rigidbody3D.__init__();
  30362. }
  30363. ShaderInit3D.__init__();
  30364. Mesh.__init__();
  30365. PrimitiveMesh.__init__();
  30366. Sprite3D.__init__();
  30367. RenderableSprite3D.__init__();
  30368. MeshSprite3D.__init__();
  30369. SkinnedMeshSprite3D.__init__();
  30370. ShuriKenParticle3D.__init__();
  30371. TrailSprite3D.__init__();
  30372. PostProcess.__init__();
  30373. Scene3D.__init__();
  30374. MeshRenderStaticBatchManager.__init__();
  30375. BaseMaterial.__initDefine__();
  30376. BlinnPhongMaterial.__initDefine__();
  30377. PBRStandardMaterial.__initDefine__();
  30378. PBRSpecularMaterial.__initDefine__();
  30379. SkyProceduralMaterial.__initDefine__();
  30380. UnlitMaterial.__initDefine__();
  30381. TrailMaterial.__initDefine__();
  30382. EffectMaterial.__initDefine__();
  30383. WaterPrimaryMaterial.__initDefine__();
  30384. ShurikenParticleMaterial.__initDefine__();
  30385. ExtendTerrainMaterial.__initDefine__();
  30386. PixelLineMaterial.__initDefine__();
  30387. SkyBoxMaterial.__initDefine__();
  30388. Command.__init__();
  30389. Laya.ClassUtils.regClass("Laya.EffectMaterial", EffectMaterial);
  30390. Laya.ClassUtils.regClass("Laya.UnlitMaterial", UnlitMaterial);
  30391. Laya.ClassUtils.regClass("Laya.BlinnPhongMaterial", BlinnPhongMaterial);
  30392. Laya.ClassUtils.regClass("Laya.SkyProceduralMaterial", SkyProceduralMaterial);
  30393. Laya.ClassUtils.regClass("Laya.PBRStandardMaterial", PBRStandardMaterial);
  30394. Laya.ClassUtils.regClass("Laya.PBRSpecularMaterial", PBRSpecularMaterial);
  30395. Laya.ClassUtils.regClass("Laya.SkyBoxMaterial", SkyBoxMaterial);
  30396. Laya.ClassUtils.regClass("Laya.WaterPrimaryMaterial", WaterPrimaryMaterial);
  30397. Laya.ClassUtils.regClass("Laya.ExtendTerrainMaterial", ExtendTerrainMaterial);
  30398. Laya.ClassUtils.regClass("Laya.ShurikenParticleMaterial", ShurikenParticleMaterial);
  30399. Laya.ClassUtils.regClass("Laya.TrailMaterial", TrailMaterial);
  30400. Laya.ClassUtils.regClass("Laya.PhysicsCollider", PhysicsCollider);
  30401. Laya.ClassUtils.regClass("Laya.Rigidbody3D", Rigidbody3D);
  30402. Laya.ClassUtils.regClass("Laya.CharacterController", CharacterController);
  30403. Laya.ClassUtils.regClass("Laya.Animator", Animator);
  30404. Laya.ClassUtils.regClass("PhysicsCollider", PhysicsCollider);
  30405. Laya.ClassUtils.regClass("CharacterController", CharacterController);
  30406. Laya.ClassUtils.regClass("Animator", Animator);
  30407. Laya.ClassUtils.regClass("Rigidbody3D", Rigidbody3D);
  30408. PixelLineMaterial.defaultMaterial = new PixelLineMaterial();
  30409. BlinnPhongMaterial.defaultMaterial = new BlinnPhongMaterial();
  30410. EffectMaterial.defaultMaterial = new EffectMaterial();
  30411. PBRStandardMaterial.defaultMaterial = new PBRStandardMaterial();
  30412. PBRSpecularMaterial.defaultMaterial = new PBRSpecularMaterial();
  30413. UnlitMaterial.defaultMaterial = new UnlitMaterial();
  30414. ShurikenParticleMaterial.defaultMaterial = new ShurikenParticleMaterial();
  30415. TrailMaterial.defaultMaterial = new TrailMaterial();
  30416. SkyProceduralMaterial.defaultMaterial = new SkyProceduralMaterial();
  30417. SkyBoxMaterial.defaultMaterial = new SkyBoxMaterial();
  30418. WaterPrimaryMaterial.defaultMaterial = new WaterPrimaryMaterial();
  30419. PixelLineMaterial.defaultMaterial.lock = true;
  30420. BlinnPhongMaterial.defaultMaterial.lock = true;
  30421. EffectMaterial.defaultMaterial.lock = true;
  30422. PBRStandardMaterial.defaultMaterial.lock = true;
  30423. PBRSpecularMaterial.defaultMaterial.lock = true;
  30424. UnlitMaterial.defaultMaterial.lock = true;
  30425. ShurikenParticleMaterial.defaultMaterial.lock = true;
  30426. TrailMaterial.defaultMaterial.lock = true;
  30427. SkyProceduralMaterial.defaultMaterial.lock = true;
  30428. SkyBoxMaterial.defaultMaterial.lock = true;
  30429. WaterPrimaryMaterial.defaultMaterial.lock = true;
  30430. Laya.Texture2D.__init__();
  30431. TextureCube.__init__();
  30432. SkyBox.__init__();
  30433. SkyDome.__init__();
  30434. ScreenQuad.__init__();
  30435. ScreenTriangle.__init__();
  30436. FrustumCulling.__init__();
  30437. HalfFloatUtils.__init__();
  30438. var createMap = Laya.LoaderManager.createMap;
  30439. createMap["lh"] = [Laya3D.HIERARCHY, Scene3DUtils._parse];
  30440. createMap["ls"] = [Laya3D.HIERARCHY, Scene3DUtils._parseScene];
  30441. createMap["lm"] = [Laya3D.MESH, Mesh._parse];
  30442. createMap["lmat"] = [Laya3D.MATERIAL, BaseMaterial._parse];
  30443. createMap["ltc"] = [Laya3D.TEXTURECUBE, TextureCube._parse];
  30444. createMap["jpg"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30445. createMap["jpeg"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30446. createMap["bmp"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30447. createMap["gif"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30448. createMap["png"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30449. createMap["dds"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30450. createMap["ktx"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30451. createMap["pvr"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30452. createMap["lani"] = [Laya3D.ANIMATIONCLIP, AnimationClip._parse];
  30453. createMap["lav"] = [Laya3D.AVATAR, Avatar._parse];
  30454. var parserMap = Laya.Loader.parserMap;
  30455. parserMap[Laya3D.HIERARCHY] = Laya3D._loadHierarchy;
  30456. parserMap[Laya3D.MESH] = Laya3D._loadMesh;
  30457. parserMap[Laya3D.MATERIAL] = Laya3D._loadMaterial;
  30458. parserMap[Laya3D.TEXTURECUBE] = Laya3D._loadTextureCube;
  30459. parserMap[Laya3D.TEXTURE2D] = Laya3D._loadTexture2D;
  30460. parserMap[Laya3D.ANIMATIONCLIP] = Laya3D._loadAnimationClip;
  30461. parserMap[Laya3D.AVATAR] = Laya3D._loadAvatar;
  30462. Laya3D._innerFirstLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  30463. Laya3D._innerSecondLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  30464. Laya3D._innerThirdLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  30465. Laya3D._innerFourthLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  30466. }
  30467. static enableNative3D() {
  30468. var shaderData = ShaderData;
  30469. var shader3D = ShaderInstance;
  30470. var skinnedMeshRender = SkinnedMeshRenderer;
  30471. var avatar = Avatar;
  30472. var frustumCulling = FrustumCulling;
  30473. if (Laya.Render.supportWebGLPlusRendering) {
  30474. shaderData.prototype._initData = shaderData.prototype._initDataForNative;
  30475. shaderData.prototype.setBool = shaderData.prototype.setBoolForNative;
  30476. shaderData.prototype.getBool = shaderData.prototype.getBoolForNative;
  30477. shaderData.prototype.setInt = shaderData.prototype.setIntForNative;
  30478. shaderData.prototype.getInt = shaderData.prototype.getIntForNative;
  30479. shaderData.prototype.setNumber = shaderData.prototype.setNumberForNative;
  30480. shaderData.prototype.getNumber = shaderData.prototype.getNumberForNative;
  30481. shaderData.prototype.setVector = shaderData.prototype.setVectorForNative;
  30482. shaderData.prototype.getVector = shaderData.prototype.getVectorForNative;
  30483. shaderData.prototype.setVector2 = shaderData.prototype.setVector2ForNative;
  30484. shaderData.prototype.getVector2 = shaderData.prototype.getVector2ForNative;
  30485. shaderData.prototype.setVector3 = shaderData.prototype.setVector3ForNative;
  30486. shaderData.prototype.getVector3 = shaderData.prototype.getVector3ForNative;
  30487. shaderData.prototype.setQuaternion = shaderData.prototype.setQuaternionForNative;
  30488. shaderData.prototype.getQuaternion = shaderData.prototype.getQuaternionForNative;
  30489. shaderData.prototype.setMatrix4x4 = shaderData.prototype.setMatrix4x4ForNative;
  30490. shaderData.prototype.getMatrix4x4 = shaderData.prototype.getMatrix4x4ForNative;
  30491. shaderData.prototype.setBuffer = shaderData.prototype.setBufferForNative;
  30492. shaderData.prototype.getBuffer = shaderData.prototype.getBufferForNative;
  30493. shaderData.prototype.setTexture = shaderData.prototype.setTextureForNative;
  30494. shaderData.prototype.getTexture = shaderData.prototype.getTextureForNative;
  30495. shaderData.prototype.setAttribute = shaderData.prototype.setAttributeForNative;
  30496. shaderData.prototype.getAttribute = shaderData.prototype.getAttributeForNative;
  30497. shaderData.prototype.cloneTo = shaderData.prototype.cloneToForNative;
  30498. shaderData.prototype.getData = shaderData.prototype.getDataForNative;
  30499. shader3D.prototype._uniformMatrix2fv = shader3D.prototype._uniformMatrix2fvForNative;
  30500. shader3D.prototype._uniformMatrix3fv = shader3D.prototype._uniformMatrix3fvForNative;
  30501. shader3D.prototype._uniformMatrix4fv = shader3D.prototype._uniformMatrix4fvForNative;
  30502. Laya.LayaGLRunner.uploadShaderUniforms = Laya.LayaGLRunner.uploadShaderUniformsForNative;
  30503. }
  30504. if (Laya.Render.supportWebGLPlusCulling) {
  30505. frustumCulling.renderObjectCulling = FrustumCulling.renderObjectCullingNative;
  30506. }
  30507. if (Laya.Render.supportWebGLPlusAnimation) {
  30508. avatar.prototype._cloneDatasToAnimator = avatar.prototype._cloneDatasToAnimatorNative;
  30509. var animationClip = AnimationClip;
  30510. animationClip.prototype._evaluateClipDatasRealTime = animationClip.prototype._evaluateClipDatasRealTimeForNative;
  30511. skinnedMeshRender.prototype._computeSkinnedData = skinnedMeshRender.prototype._computeSkinnedDataForNative;
  30512. }
  30513. if (Laya.Render.isConchApp) {
  30514. Laya.WebGL.shaderHighPrecision = false;
  30515. var gl = Laya.LayaGL.instance;
  30516. var precisionFormat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
  30517. precisionFormat.precision ? Laya.WebGL.shaderHighPrecision = true : Laya.WebGL.shaderHighPrecision = false;
  30518. }
  30519. }
  30520. static formatRelativePath(base, value) {
  30521. var path;
  30522. path = base + value;
  30523. var char1 = value.charAt(0);
  30524. if (char1 === ".") {
  30525. var parts = path.split("/");
  30526. for (var i = 0, len = parts.length; i < len; i++) {
  30527. if (parts[i] == '..') {
  30528. var index = i - 1;
  30529. if (index > 0 && parts[index] !== '..') {
  30530. parts.splice(index, 2);
  30531. i -= 2;
  30532. }
  30533. }
  30534. }
  30535. path = parts.join('/');
  30536. }
  30537. return path;
  30538. }
  30539. static _endLoad(loader, content = null, subResous = null) {
  30540. if (subResous) {
  30541. for (var i = 0, n = subResous.length; i < n; i++) {
  30542. var resou = Laya.Loader.getRes(subResous[i]);
  30543. (resou) && (resou._removeReference());
  30544. }
  30545. }
  30546. loader.endLoad(content);
  30547. }
  30548. static _eventLoadManagerError(msg) {
  30549. Laya.Laya.loader.event(Laya.Event.ERROR, msg);
  30550. }
  30551. static _addHierarchyInnerUrls(urls, urlMap, urlVersion, hierarchyBasePath, path, type, constructParams = null, propertyParams = null) {
  30552. var formatUrl = Laya3D.formatRelativePath(hierarchyBasePath, path);
  30553. (urlVersion) && (formatUrl = formatUrl + urlVersion);
  30554. urls.push({ url: formatUrl, type: type, constructParams: constructParams, propertyParams: propertyParams });
  30555. urlMap.push(formatUrl);
  30556. return formatUrl;
  30557. }
  30558. static _getSprite3DHierarchyInnerUrls(node, firstLevelUrls, secondLevelUrls, thirdLevelUrls, fourthLelUrls, subUrls, urlVersion, hierarchyBasePath) {
  30559. var i, n;
  30560. var props = node.props;
  30561. switch (node.type) {
  30562. case "Scene3D":
  30563. var lightmaps = props.lightmaps;
  30564. for (i = 0, n = lightmaps.length; i < n; i++) {
  30565. var lightMap = lightmaps[i];
  30566. lightMap.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, lightMap.path, Laya3D.TEXTURE2D, lightMap.constructParams, lightMap.propertyParams);
  30567. }
  30568. var reflectionTextureData = props.reflectionTexture;
  30569. (reflectionTextureData) && (props.reflectionTexture = Laya3D._addHierarchyInnerUrls(thirdLevelUrls, subUrls, urlVersion, hierarchyBasePath, reflectionTextureData, Laya3D.TEXTURECUBE));
  30570. if (props.sky) {
  30571. var skyboxMaterial = props.sky.material;
  30572. (skyboxMaterial) && (skyboxMaterial.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, skyboxMaterial.path, Laya3D.MATERIAL));
  30573. }
  30574. break;
  30575. case "Camera":
  30576. var skyboxMatData = props.skyboxMaterial;
  30577. (skyboxMatData) && (skyboxMatData.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, skyboxMatData.path, Laya3D.MATERIAL));
  30578. break;
  30579. case "TrailSprite3D":
  30580. case "MeshSprite3D":
  30581. case "SkinnedMeshSprite3D":
  30582. var meshPath = props.meshPath;
  30583. (meshPath) && (props.meshPath = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, meshPath, Laya3D.MESH));
  30584. var materials = props.materials;
  30585. if (materials)
  30586. for (i = 0, n = materials.length; i < n; i++)
  30587. materials[i].path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, materials[i].path, Laya3D.MATERIAL);
  30588. break;
  30589. case "ShuriKenParticle3D":
  30590. var parMeshPath = props.meshPath;
  30591. (parMeshPath) && (props.meshPath = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, parMeshPath, Laya3D.MESH));
  30592. props.material.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, props.material.path, Laya3D.MATERIAL);
  30593. break;
  30594. case "Terrain":
  30595. Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, props.dataPath, Laya3D.TERRAINRES);
  30596. break;
  30597. }
  30598. var components = node.components;
  30599. if (components) {
  30600. for (var k = 0, p = components.length; k < p; k++) {
  30601. var component = components[k];
  30602. switch (component.type) {
  30603. case "Animator":
  30604. var avatarPath = component.avatarPath;
  30605. var avatarData = component.avatar;
  30606. (avatarData) && (avatarData.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, avatarData.path, Laya3D.AVATAR));
  30607. var clipPaths = component.clipPaths;
  30608. if (!clipPaths) {
  30609. var layersData = component.layers;
  30610. for (i = 0; i < layersData.length; i++) {
  30611. var states = layersData[i].states;
  30612. for (var j = 0, m = states.length; j < m; j++) {
  30613. var clipPath = states[j].clipPath;
  30614. (clipPath) && (states[j].clipPath = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, clipPath, Laya3D.ANIMATIONCLIP));
  30615. }
  30616. }
  30617. }
  30618. else {
  30619. for (i = 0, n = clipPaths.length; i < n; i++)
  30620. clipPaths[i] = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, clipPaths[i], Laya3D.ANIMATIONCLIP);
  30621. }
  30622. break;
  30623. case "PhysicsCollider":
  30624. case "Rigidbody3D":
  30625. case "CharacterController":
  30626. var shapes = component.shapes;
  30627. for (i = 0; i < shapes.length; i++) {
  30628. var shape = shapes[i];
  30629. if (shape.type === "MeshColliderShape") {
  30630. var mesh = shape.mesh;
  30631. (mesh) && (shape.mesh = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, mesh, Laya3D.MESH));
  30632. }
  30633. }
  30634. break;
  30635. }
  30636. }
  30637. }
  30638. var children = node.child;
  30639. for (i = 0, n = children.length; i < n; i++)
  30640. Laya3D._getSprite3DHierarchyInnerUrls(children[i], firstLevelUrls, secondLevelUrls, thirdLevelUrls, fourthLelUrls, subUrls, urlVersion, hierarchyBasePath);
  30641. }
  30642. static _loadHierarchy(loader) {
  30643. loader.on(Laya.Event.LOADED, null, Laya3D._onHierarchylhLoaded, [loader]);
  30644. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  30645. }
  30646. static _onHierarchylhLoaded(loader, lhData) {
  30647. var url = loader.url;
  30648. var urlVersion = Utils3D.getURLVerion(url);
  30649. var hierarchyBasePath = Laya.URL.getPath(url);
  30650. var firstLevUrls = [];
  30651. var secondLevUrls = [];
  30652. var thirdLevUrls = [];
  30653. var forthLevUrls = [];
  30654. var subUrls = [];
  30655. Laya3D._getSprite3DHierarchyInnerUrls(lhData.data, firstLevUrls, secondLevUrls, thirdLevUrls, forthLevUrls, subUrls, urlVersion, hierarchyBasePath);
  30656. var urlCount = firstLevUrls.length + secondLevUrls.length + forthLevUrls.length;
  30657. var totalProcessCount = urlCount + 1;
  30658. var weight = 1 / totalProcessCount;
  30659. Laya3D._onProcessChange(loader, 0, weight, 1.0);
  30660. if (forthLevUrls.length > 0) {
  30661. var processCeil = urlCount / totalProcessCount;
  30662. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, weight, processCeil], false);
  30663. 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);
  30664. }
  30665. else {
  30666. Laya3D._onHierarchyInnerForthLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, secondLevUrls, thirdLevUrls, weight, processCeil);
  30667. }
  30668. }
  30669. static _onHierarchyInnerForthLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, secondLevUrls, thirdLevUrls, processOffset, processCeil) {
  30670. (processHandler) && (processHandler.recover());
  30671. if (thirdLevUrls.length > 0) {
  30672. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  30673. 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);
  30674. }
  30675. else {
  30676. Laya3D._onHierarchyInnerThirdLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, secondLevUrls, processOffset, processCeil);
  30677. }
  30678. }
  30679. static _onHierarchyInnerThirdLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, secondLevUrls, processOffset, processCeil) {
  30680. (processHandler) && (processHandler.recover());
  30681. if (secondLevUrls.length > 0) {
  30682. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  30683. 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);
  30684. }
  30685. else {
  30686. Laya3D._onHierarchyInnerSecondLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, processOffset, processCeil);
  30687. }
  30688. }
  30689. static _onHierarchyInnerSecondLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, processOffset, processCeil) {
  30690. (processHandler) && (processHandler.recover());
  30691. if (firstLevUrls.length > 0) {
  30692. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  30693. Laya3D._innerFirstLevelLoaderManager._create(firstLevUrls, false, Laya.Handler.create(null, Laya3D._onHierarchyInnerFirstLevResouLoaded, [loader, process, lhData, subUrls]), processHandler, null, null, null, 1, true);
  30694. }
  30695. else {
  30696. Laya3D._onHierarchyInnerFirstLevResouLoaded(loader, null, lhData, subUrls);
  30697. }
  30698. }
  30699. static _onHierarchyInnerFirstLevResouLoaded(loader, processHandler, lhData, subUrls) {
  30700. (processHandler) && (processHandler.recover());
  30701. loader._cache = loader._createCache;
  30702. var item = lhData.data.type === "Scene3D" ? Scene3DUtils._parseScene(lhData, loader._propertyParams, loader._constructParams) : Scene3DUtils._parse(lhData, loader._propertyParams, loader._constructParams);
  30703. Laya3D._endLoad(loader, item, subUrls);
  30704. }
  30705. static _loadMesh(loader) {
  30706. loader.on(Laya.Event.LOADED, null, Laya3D._onMeshLmLoaded, [loader]);
  30707. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  30708. }
  30709. static _onMeshLmLoaded(loader, lmData) {
  30710. loader._cache = loader._createCache;
  30711. var mesh = Mesh._parse(lmData, loader._propertyParams, loader._constructParams);
  30712. Laya3D._endLoad(loader, mesh);
  30713. }
  30714. static _loadMaterial(loader) {
  30715. loader.on(Laya.Event.LOADED, null, Laya3D._onMaterilLmatLoaded, [loader]);
  30716. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  30717. }
  30718. static _onMaterilLmatLoaded(loader, lmatData) {
  30719. var url = loader.url;
  30720. var urlVersion = Utils3D.getURLVerion(url);
  30721. var materialBasePath = Laya.URL.getPath(url);
  30722. var urls = [];
  30723. var subUrls = [];
  30724. var customProps = lmatData.customProps;
  30725. var formatSubUrl;
  30726. var version = lmatData.version;
  30727. switch (version) {
  30728. case "LAYAMATERIAL:01":
  30729. case "LAYAMATERIAL:02":
  30730. var i, n;
  30731. var textures = lmatData.props.textures;
  30732. if (textures) {
  30733. for (i = 0, n = textures.length; i < n; i++) {
  30734. var tex2D = textures[i];
  30735. var tex2DPath = tex2D.path;
  30736. if (tex2DPath) {
  30737. formatSubUrl = Laya3D.formatRelativePath(materialBasePath, tex2DPath);
  30738. (urlVersion) && (formatSubUrl = formatSubUrl + urlVersion);
  30739. urls.push({ url: formatSubUrl, constructParams: tex2D.constructParams, propertyParams: tex2D.propertyParams });
  30740. subUrls.push(formatSubUrl);
  30741. tex2D.path = formatSubUrl;
  30742. }
  30743. }
  30744. }
  30745. break;
  30746. default:
  30747. throw new Error("Laya3D:unkonwn version.");
  30748. }
  30749. var urlCount = urls.length;
  30750. var totalProcessCount = urlCount + 1;
  30751. var lmatWeight = 1 / totalProcessCount;
  30752. Laya3D._onProcessChange(loader, 0, lmatWeight, 1.0);
  30753. if (urlCount > 0) {
  30754. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, lmatWeight, urlCount / totalProcessCount], false);
  30755. Laya3D._innerFourthLevelLoaderManager._create(urls, false, Laya.Handler.create(null, Laya3D._onMateialTexturesLoaded, [loader, processHandler, lmatData, subUrls]), processHandler, null, null, null, 1, true);
  30756. }
  30757. else {
  30758. Laya3D._onMateialTexturesLoaded(loader, null, lmatData, null);
  30759. }
  30760. }
  30761. static _onMateialTexturesLoaded(loader, processHandler, lmatData, subUrls) {
  30762. loader._cache = loader._createCache;
  30763. var mat = BaseMaterial._parse(lmatData, loader._propertyParams, loader._constructParams);
  30764. Laya3D._endLoad(loader, mat, subUrls);
  30765. (processHandler) && (processHandler.recover());
  30766. }
  30767. static _loadAvatar(loader) {
  30768. loader.on(Laya.Event.LOADED, null, function (data) {
  30769. loader._cache = loader._createCache;
  30770. var avatar = Avatar._parse(data, loader._propertyParams, loader._constructParams);
  30771. Laya3D._endLoad(loader, avatar);
  30772. });
  30773. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  30774. }
  30775. static _loadAnimationClip(loader) {
  30776. loader.on(Laya.Event.LOADED, null, function (data) {
  30777. loader._cache = loader._createCache;
  30778. var clip = AnimationClip._parse(data, loader._propertyParams, loader._constructParams);
  30779. Laya3D._endLoad(loader, clip);
  30780. });
  30781. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  30782. }
  30783. static _loadTexture2D(loader) {
  30784. var url = loader.url;
  30785. var index = url.lastIndexOf('.') + 1;
  30786. var verIndex = url.indexOf('?');
  30787. var endIndex = verIndex == -1 ? url.length : verIndex;
  30788. var ext = url.substr(index, endIndex - index);
  30789. var type;
  30790. switch (ext) {
  30791. case "jpg":
  30792. case "jpeg":
  30793. case "bmp":
  30794. case "gif":
  30795. case "png":
  30796. type = "nativeimage";
  30797. break;
  30798. case "dds":
  30799. case "ktx":
  30800. case "pvr":
  30801. type = Laya.Loader.BUFFER;
  30802. break;
  30803. }
  30804. loader.on(Laya.Event.LOADED, null, function (image) {
  30805. loader._cache = loader._createCache;
  30806. var tex = Laya.Texture2D._parse(image, loader._propertyParams, loader._constructParams);
  30807. Laya3D._endLoad(loader, tex);
  30808. });
  30809. loader.load(loader.url, type, false, null, true);
  30810. }
  30811. static _loadTextureCube(loader) {
  30812. loader.on(Laya.Event.LOADED, null, Laya3D._onTextureCubeLtcLoaded, [loader]);
  30813. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  30814. }
  30815. static _onTextureCubeLtcLoaded(loader, ltcData) {
  30816. var ltcBasePath = Laya.URL.getPath(loader.url);
  30817. 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)];
  30818. var ltcWeight = 1.0 / 7.0;
  30819. Laya3D._onProcessChange(loader, 0, ltcWeight, 1.0);
  30820. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, ltcWeight, 6 / 7], false);
  30821. Laya3D._innerFourthLevelLoaderManager.load(urls, Laya.Handler.create(null, Laya3D._onTextureCubeImagesLoaded, [loader, urls, processHandler]), processHandler, "nativeimage");
  30822. }
  30823. static _onTextureCubeImagesLoaded(loader, urls, processHandler) {
  30824. var images = new Array(6);
  30825. for (var i = 0; i < 6; i++)
  30826. images[i] = Laya.Loader.getRes(urls[i]);
  30827. loader._cache = loader._createCache;
  30828. var tex = TextureCube._parse(images, loader._propertyParams, loader._constructParams);
  30829. processHandler.recover();
  30830. for (i = 0; i < 6; i++)
  30831. Laya.Loader.clearRes(urls[i]);
  30832. Laya3D._endLoad(loader, tex);
  30833. }
  30834. static _onProcessChange(loader, offset, weight, process) {
  30835. process = offset + process * weight;
  30836. (process < 1.0) && (loader.event(Laya.Event.PROGRESS, process));
  30837. }
  30838. static init(width, height, config = null, compolete = null) {
  30839. if (Laya3D._isInit)
  30840. return;
  30841. Laya3D._isInit = true;
  30842. (config) && (config.cloneTo(Config3D._config));
  30843. config = Config3D._config;
  30844. FrustumCulling.debugFrustumCulling = config.debugFrustumCulling;
  30845. Laya3D._editerEnvironment = config._editerEnvironment;
  30846. Scene3D.octreeCulling = config.octreeCulling;
  30847. Scene3D.octreeInitialSize = config.octreeInitialSize;
  30848. Scene3D.octreeInitialCenter = config.octreeInitialCenter;
  30849. Scene3D.octreeMinNodeSize = config.octreeMinNodeSize;
  30850. Scene3D.octreeLooseness = config.octreeLooseness;
  30851. var physics3D = window.Physics3D;
  30852. if (physics3D == null) {
  30853. Physics3D._enbalePhysics = false;
  30854. Laya3D.__init__(width, height, config);
  30855. compolete && compolete.run();
  30856. }
  30857. else {
  30858. Physics3D._enbalePhysics = true;
  30859. physics3D(config.defaultPhysicsMemory * 1024 * 1024).then(function () {
  30860. Laya3D.__init__(width, height, config);
  30861. compolete && compolete.run();
  30862. });
  30863. }
  30864. }
  30865. }
  30866. Laya3D.HIERARCHY = "HIERARCHY";
  30867. Laya3D.MESH = "MESH";
  30868. Laya3D.MATERIAL = "MATERIAL";
  30869. Laya3D.TEXTURE2D = "TEXTURE2D";
  30870. Laya3D.TEXTURECUBE = "TEXTURECUBE";
  30871. Laya3D.ANIMATIONCLIP = "ANIMATIONCLIP";
  30872. Laya3D.AVATAR = "AVATAR";
  30873. Laya3D.TERRAINHEIGHTDATA = "TERRAINHEIGHTDATA";
  30874. Laya3D.TERRAINRES = "TERRAIN";
  30875. Laya3D._innerFirstLevelLoaderManager = new Laya.LoaderManager();
  30876. Laya3D._innerSecondLevelLoaderManager = new Laya.LoaderManager();
  30877. Laya3D._innerThirdLevelLoaderManager = new Laya.LoaderManager();
  30878. Laya3D._innerFourthLevelLoaderManager = new Laya.LoaderManager();
  30879. Laya3D._isInit = false;
  30880. Laya3D._editerEnvironment = false;
  30881. Laya3D.physicsSettings = new PhysicsSettings();
  30882. window.Laya3D = Laya3D;
  30883. class AnimatorStateScript {
  30884. constructor() {
  30885. }
  30886. onStateEnter() {
  30887. }
  30888. onStateUpdate() {
  30889. }
  30890. onStateExit() {
  30891. }
  30892. }
  30893. class Script3D extends Laya.Component {
  30894. constructor() {
  30895. super(...arguments);
  30896. this._indexInPool = -1;
  30897. }
  30898. get isSingleton() {
  30899. return false;
  30900. }
  30901. _checkProcessTriggers() {
  30902. var prototype = Script3D.prototype;
  30903. if (this.onTriggerEnter !== prototype.onTriggerEnter)
  30904. return true;
  30905. if (this.onTriggerStay !== prototype.onTriggerStay)
  30906. return true;
  30907. if (this.onTriggerExit !== prototype.onTriggerExit)
  30908. return true;
  30909. return false;
  30910. }
  30911. _checkProcessCollisions() {
  30912. var prototype = Script3D.prototype;
  30913. if (this.onCollisionEnter !== prototype.onCollisionEnter)
  30914. return true;
  30915. if (this.onCollisionStay !== prototype.onCollisionStay)
  30916. return true;
  30917. if (this.onCollisionExit !== prototype.onCollisionExit)
  30918. return true;
  30919. return false;
  30920. }
  30921. _onAwake() {
  30922. this.onAwake();
  30923. if (this.onStart !== Script3D.prototype.onStart)
  30924. Laya.Laya.startTimer.callLater(this, this.onStart);
  30925. }
  30926. _onEnable() {
  30927. this.owner._scene._addScript(this);
  30928. var proto = Script3D.prototype;
  30929. if (this.onKeyDown !== proto.onKeyDown) {
  30930. Laya.Laya.stage.on(Laya.Event.KEY_DOWN, this, this.onKeyDown);
  30931. }
  30932. if (this.onKeyPress !== proto.onKeyPress) {
  30933. Laya.Laya.stage.on(Laya.Event.KEY_PRESS, this, this.onKeyUp);
  30934. }
  30935. if (this.onKeyUp !== proto.onKeyUp) {
  30936. Laya.Laya.stage.on(Laya.Event.KEY_UP, this, this.onKeyUp);
  30937. }
  30938. }
  30939. _onDisable() {
  30940. this.owner._scene._removeScript(this);
  30941. this.owner.offAllCaller(this);
  30942. Laya.Laya.stage.offAllCaller(this);
  30943. }
  30944. _isScript() {
  30945. return true;
  30946. }
  30947. _onAdded() {
  30948. var sprite = this.owner;
  30949. var scripts = sprite._scripts;
  30950. scripts || (sprite._scripts = scripts = []);
  30951. scripts.push(this);
  30952. if (!sprite._needProcessCollisions)
  30953. sprite._needProcessCollisions = this._checkProcessCollisions();
  30954. if (!sprite._needProcessTriggers)
  30955. sprite._needProcessTriggers = this._checkProcessTriggers();
  30956. }
  30957. _onDestroy() {
  30958. var scripts = this.owner._scripts;
  30959. scripts.splice(scripts.indexOf(this), 1);
  30960. var sprite = this.owner;
  30961. sprite._needProcessTriggers = false;
  30962. for (var i = 0, n = scripts.length; i < n; i++) {
  30963. if (scripts[i]._checkProcessTriggers()) {
  30964. sprite._needProcessTriggers = true;
  30965. break;
  30966. }
  30967. }
  30968. sprite._needProcessCollisions = false;
  30969. for (i = 0, n = scripts.length; i < n; i++) {
  30970. if (scripts[i]._checkProcessCollisions()) {
  30971. sprite._needProcessCollisions = true;
  30972. break;
  30973. }
  30974. }
  30975. this.onDestroy();
  30976. }
  30977. onAwake() {
  30978. }
  30979. onEnable() {
  30980. }
  30981. onStart() {
  30982. }
  30983. onTriggerEnter(other) {
  30984. }
  30985. onTriggerStay(other) {
  30986. }
  30987. onTriggerExit(other) {
  30988. }
  30989. onCollisionEnter(collision) {
  30990. }
  30991. onCollisionStay(collision) {
  30992. }
  30993. onCollisionExit(collision) {
  30994. }
  30995. onMouseDown() {
  30996. }
  30997. onMouseDrag() {
  30998. }
  30999. onMouseClick() {
  31000. }
  31001. onMouseUp() {
  31002. }
  31003. onMouseEnter() {
  31004. }
  31005. onMouseOver() {
  31006. }
  31007. onMouseOut() {
  31008. }
  31009. onKeyDown(e) {
  31010. }
  31011. onKeyPress(e) {
  31012. }
  31013. onKeyUp(e) {
  31014. }
  31015. onUpdate() {
  31016. }
  31017. onLateUpdate() {
  31018. }
  31019. onPreRender() {
  31020. }
  31021. onPostRender() {
  31022. }
  31023. onDisable() {
  31024. }
  31025. onDestroy() {
  31026. }
  31027. }
  31028. class HeightMap {
  31029. constructor(width, height, minHeight, maxHeight) {
  31030. this._datas = [];
  31031. this._w = width;
  31032. this._h = height;
  31033. this._minHeight = minHeight;
  31034. this._maxHeight = maxHeight;
  31035. }
  31036. static creatFromMesh(mesh, width, height, outCellSize) {
  31037. var vertices = [];
  31038. var indexs = [];
  31039. var submesheCount = mesh.subMeshCount;
  31040. for (var i = 0; i < submesheCount; i++) {
  31041. var subMesh = mesh.getSubMesh(i);
  31042. var vertexBuffer = subMesh._vertexBuffer;
  31043. var verts = vertexBuffer.getFloat32Data();
  31044. var subMeshVertices = [];
  31045. for (var j = 0; j < verts.length; j += vertexBuffer.vertexDeclaration.vertexStride / 4) {
  31046. var position = new Vector3(verts[j + 0], verts[j + 1], verts[j + 2]);
  31047. subMeshVertices.push(position);
  31048. }
  31049. vertices.push(subMeshVertices);
  31050. var ib = subMesh._indexBuffer;
  31051. indexs.push(ib.getData());
  31052. }
  31053. var bounds = mesh.bounds;
  31054. var minX = bounds.getMin().x;
  31055. var minZ = bounds.getMin().z;
  31056. var maxX = bounds.getMax().x;
  31057. var maxZ = bounds.getMax().z;
  31058. var minY = bounds.getMin().y;
  31059. var maxY = bounds.getMax().y;
  31060. var widthSize = maxX - minX;
  31061. var heightSize = maxZ - minZ;
  31062. var cellWidth = outCellSize.x = widthSize / (width - 1);
  31063. var cellHeight = outCellSize.y = heightSize / (height - 1);
  31064. var heightMap = new HeightMap(width, height, minY, maxY);
  31065. var ray = HeightMap._tempRay;
  31066. var rayDir = ray.direction;
  31067. rayDir.x = 0;
  31068. rayDir.y = -1;
  31069. rayDir.z = 0;
  31070. const heightOffset = 0.1;
  31071. var rayY = maxY + heightOffset;
  31072. ray.origin.y = rayY;
  31073. for (var h = 0; h < height; h++) {
  31074. var posZ = minZ + h * cellHeight;
  31075. heightMap._datas[h] = [];
  31076. for (var w = 0; w < width; w++) {
  31077. var posX = minX + w * cellWidth;
  31078. var rayOri = ray.origin;
  31079. rayOri.x = posX;
  31080. rayOri.z = posZ;
  31081. var closestIntersection = HeightMap._getPosition(ray, vertices, indexs);
  31082. heightMap._datas[h][w] = (closestIntersection === Number.MAX_VALUE) ? NaN : rayY - closestIntersection;
  31083. }
  31084. }
  31085. return heightMap;
  31086. }
  31087. static createFromImage(texture, minHeight, maxHeight) {
  31088. var textureWidth = texture.width;
  31089. var textureHeight = texture.height;
  31090. var heightMap = new HeightMap(textureWidth, textureHeight, minHeight, maxHeight);
  31091. var compressionRatio = (maxHeight - minHeight) / 254;
  31092. var pixelsInfo = texture.getPixels();
  31093. var index = 0;
  31094. for (var h = 0; h < textureHeight; h++) {
  31095. var colDatas = heightMap._datas[h] = [];
  31096. for (var w = 0; w < textureWidth; w++) {
  31097. var r = pixelsInfo[index++];
  31098. var g = pixelsInfo[index++];
  31099. var b = pixelsInfo[index++];
  31100. var a = pixelsInfo[index++];
  31101. if (r == 255 && g == 255 && b == 255 && a == 255)
  31102. colDatas[w] = NaN;
  31103. else {
  31104. colDatas[w] = (r + g + b) / 3 * compressionRatio + minHeight;
  31105. }
  31106. }
  31107. }
  31108. return heightMap;
  31109. }
  31110. static _getPosition(ray, vertices, indexs) {
  31111. var closestIntersection = Number.MAX_VALUE;
  31112. for (var i = 0; i < vertices.length; i++) {
  31113. var subMeshVertices = vertices[i];
  31114. var subMeshIndexes = indexs[i];
  31115. for (var j = 0; j < subMeshIndexes.length; j += 3) {
  31116. var vertex1 = subMeshVertices[subMeshIndexes[j + 0]];
  31117. var vertex2 = subMeshVertices[subMeshIndexes[j + 1]];
  31118. var vertex3 = subMeshVertices[subMeshIndexes[j + 2]];
  31119. var intersection = Picker.rayIntersectsTriangle(ray, vertex1, vertex2, vertex3);
  31120. if (!isNaN(intersection) && intersection < closestIntersection) {
  31121. closestIntersection = intersection;
  31122. }
  31123. }
  31124. }
  31125. return closestIntersection;
  31126. }
  31127. get width() {
  31128. return this._w;
  31129. }
  31130. get height() {
  31131. return this._h;
  31132. }
  31133. get maxHeight() {
  31134. return this._maxHeight;
  31135. }
  31136. get minHeight() {
  31137. return this._minHeight;
  31138. }
  31139. _inBounds(row, col) {
  31140. return row >= 0 && row < this._h && col >= 0 && col < this._w;
  31141. }
  31142. getHeight(row, col) {
  31143. if (this._inBounds(row, col))
  31144. return this._datas[row][col];
  31145. else
  31146. return NaN;
  31147. }
  31148. }
  31149. HeightMap._tempRay = new Ray(new Vector3(), new Vector3());
  31150. class MeshTerrainSprite3D extends MeshSprite3D {
  31151. constructor(mesh, heightMap, name = null) {
  31152. super(mesh, name);
  31153. this._heightMap = heightMap;
  31154. this._cellSize = new Vector2();
  31155. }
  31156. static createFromMesh(mesh, heightMapWidth, heightMapHeight, name = null) {
  31157. var meshTerrainSprite3D = new MeshTerrainSprite3D(mesh, null, name);
  31158. meshTerrainSprite3D._initCreateFromMesh(heightMapWidth, heightMapHeight);
  31159. return meshTerrainSprite3D;
  31160. }
  31161. static createFromMeshAndHeightMap(mesh, texture, minHeight, maxHeight, name = null) {
  31162. var meshTerrainSprite3D = new MeshTerrainSprite3D(mesh, null, name);
  31163. meshTerrainSprite3D._initCreateFromMeshHeightMap(texture, minHeight, maxHeight);
  31164. return meshTerrainSprite3D;
  31165. }
  31166. get minX() {
  31167. var worldMat = this.transform.worldMatrix;
  31168. var worldMatE = worldMat.elements;
  31169. return this._minX * this._getScaleX() + worldMatE[12];
  31170. }
  31171. get minZ() {
  31172. var worldMat = this.transform.worldMatrix;
  31173. var worldMatE = worldMat.elements;
  31174. return this._minZ * this._getScaleZ() + worldMatE[14];
  31175. }
  31176. get width() {
  31177. return (this._heightMap.width - 1) * this._cellSize.x * this._getScaleX();
  31178. }
  31179. get depth() {
  31180. return (this._heightMap.height - 1) * this._cellSize.y * this._getScaleZ();
  31181. }
  31182. _disableRotation() {
  31183. var rotation = this.transform.rotation;
  31184. rotation.x = 0;
  31185. rotation.y = 0;
  31186. rotation.z = 0;
  31187. rotation.w = 1;
  31188. this.transform.rotation = rotation;
  31189. }
  31190. _getScaleX() {
  31191. var worldMat = this.transform.worldMatrix;
  31192. var worldMatE = worldMat.elements;
  31193. var m11 = worldMatE[0];
  31194. var m12 = worldMatE[1];
  31195. var m13 = worldMatE[2];
  31196. return Math.sqrt((m11 * m11) + (m12 * m12) + (m13 * m13));
  31197. }
  31198. _getScaleZ() {
  31199. var worldMat = this.transform.worldMatrix;
  31200. var worldMatE = worldMat.elements;
  31201. var m31 = worldMatE[8];
  31202. var m32 = worldMatE[9];
  31203. var m33 = worldMatE[10];
  31204. return Math.sqrt((m31 * m31) + (m32 * m32) + (m33 * m33));
  31205. }
  31206. _initCreateFromMesh(heightMapWidth, heightMapHeight) {
  31207. this._heightMap = HeightMap.creatFromMesh(this.meshFilter.sharedMesh, heightMapWidth, heightMapHeight, this._cellSize);
  31208. var boundingBox = this.meshFilter.sharedMesh.bounds;
  31209. var min = boundingBox.getMin();
  31210. var max = boundingBox.getMax();
  31211. this._minX = min.x;
  31212. this._minZ = min.z;
  31213. }
  31214. _initCreateFromMeshHeightMap(texture, minHeight, maxHeight) {
  31215. var boundingBox = this.meshFilter.sharedMesh.bounds;
  31216. this._heightMap = HeightMap.createFromImage(texture, minHeight, maxHeight);
  31217. this._computeCellSize(boundingBox);
  31218. var min = boundingBox.getMin();
  31219. var max = boundingBox.getMax();
  31220. this._minX = min.x;
  31221. this._minZ = min.z;
  31222. }
  31223. _computeCellSize(boundingBox) {
  31224. var min = boundingBox.getMin();
  31225. var max = boundingBox.getMax();
  31226. var minX = min.x;
  31227. var minZ = min.z;
  31228. var maxX = max.x;
  31229. var maxZ = max.z;
  31230. var widthSize = maxX - minX;
  31231. var heightSize = maxZ - minZ;
  31232. this._cellSize.x = widthSize / (this._heightMap.width - 1);
  31233. this._cellSize.y = heightSize / (this._heightMap.height - 1);
  31234. }
  31235. _update(state) {
  31236. this._disableRotation();
  31237. }
  31238. getHeight(x, z) {
  31239. MeshTerrainSprite3D._tempVector3.x = x;
  31240. MeshTerrainSprite3D._tempVector3.y = 0;
  31241. MeshTerrainSprite3D._tempVector3.z = z;
  31242. this._disableRotation();
  31243. var worldMat = this.transform.worldMatrix;
  31244. worldMat.invert(MeshTerrainSprite3D._tempMatrix4x4);
  31245. Vector3.transformCoordinate(MeshTerrainSprite3D._tempVector3, MeshTerrainSprite3D._tempMatrix4x4, MeshTerrainSprite3D._tempVector3);
  31246. x = MeshTerrainSprite3D._tempVector3.x;
  31247. z = MeshTerrainSprite3D._tempVector3.z;
  31248. var c = (x - this._minX) / this._cellSize.x;
  31249. var d = (z - this._minZ) / this._cellSize.y;
  31250. var row = Math.floor(d);
  31251. var col = Math.floor(c);
  31252. var s = c - col;
  31253. var t = d - row;
  31254. var uy;
  31255. var vy;
  31256. var worldMatE = worldMat.elements;
  31257. var m21 = worldMatE[4];
  31258. var m22 = worldMatE[5];
  31259. var m23 = worldMatE[6];
  31260. var scaleY = Math.sqrt((m21 * m21) + (m22 * m22) + (m23 * m23));
  31261. var translateY = worldMatE[13];
  31262. var h01 = this._heightMap.getHeight(row, col + 1);
  31263. var h10 = this._heightMap.getHeight((row + 1), col);
  31264. if (isNaN(h01) || isNaN(h10))
  31265. return NaN;
  31266. if (s + t <= 1.0) {
  31267. var h00 = this._heightMap.getHeight(row, col);
  31268. if (isNaN(h00))
  31269. return NaN;
  31270. uy = h01 - h00;
  31271. vy = h10 - h00;
  31272. return (h00 + s * uy + t * vy) * scaleY + translateY;
  31273. }
  31274. else {
  31275. var h11 = this._heightMap.getHeight((row + 1), col + 1);
  31276. if (isNaN(h11))
  31277. return NaN;
  31278. uy = h10 - h11;
  31279. vy = h01 - h11;
  31280. return (h11 + (1.0 - s) * uy + (1.0 - t) * vy) * scaleY + translateY;
  31281. }
  31282. }
  31283. }
  31284. MeshTerrainSprite3D._tempVector3 = new Vector3();
  31285. MeshTerrainSprite3D._tempMatrix4x4 = new Matrix4x4();
  31286. class GradientDataVector2 {
  31287. constructor() {
  31288. this._currentLength = 0;
  31289. this._elements = new Float32Array(12);
  31290. }
  31291. get gradientCount() {
  31292. return this._currentLength / 3;
  31293. }
  31294. add(key, value) {
  31295. if (this._currentLength < 8) {
  31296. if ((this._currentLength === 6) && ((key !== 1))) {
  31297. key = 1;
  31298. console.log("GradientDataVector2 warning:the forth key is be force set to 1.");
  31299. }
  31300. this._elements[this._currentLength++] = key;
  31301. this._elements[this._currentLength++] = value.x;
  31302. this._elements[this._currentLength++] = value.y;
  31303. }
  31304. else {
  31305. console.log("GradientDataVector2 warning:data count must lessEqual than 4");
  31306. }
  31307. }
  31308. cloneTo(destObject) {
  31309. var destGradientDataVector2 = destObject;
  31310. destGradientDataVector2._currentLength = this._currentLength;
  31311. var destElements = destGradientDataVector2._elements;
  31312. for (var i = 0, n = this._elements.length; i < n; i++) {
  31313. destElements[i] = this._elements[i];
  31314. }
  31315. }
  31316. clone() {
  31317. var destGradientDataVector2 = new GradientDataVector2();
  31318. this.cloneTo(destGradientDataVector2);
  31319. return destGradientDataVector2;
  31320. }
  31321. }
  31322. class PixelLineData {
  31323. constructor() {
  31324. this.startPosition = new Vector3();
  31325. this.endPosition = new Vector3();
  31326. this.startColor = new Color();
  31327. this.endColor = new Color();
  31328. }
  31329. cloneTo(destObject) {
  31330. this.startPosition.cloneTo(destObject.startPosition);
  31331. this.endPosition.cloneTo(destObject.endPosition);
  31332. this.startColor.cloneTo(destObject.startColor);
  31333. this.endColor.cloneTo(destObject.endColor);
  31334. }
  31335. }
  31336. class PostProcessEffect {
  31337. constructor() {
  31338. }
  31339. render(context) {
  31340. }
  31341. }
  31342. class BloomEffect extends PostProcessEffect {
  31343. constructor() {
  31344. super();
  31345. this._shader = null;
  31346. this._shaderData = new ShaderData();
  31347. this._linearColor = new Color();
  31348. this._bloomTextureTexelSize = new Vector4();
  31349. this._shaderThreshold = new Vector4();
  31350. this._shaderParams = new Vector4();
  31351. this._pyramid = null;
  31352. this._intensity = 0.0;
  31353. this._threshold = 1.0;
  31354. this._softKnee = 0.5;
  31355. this._diffusion = 7.0;
  31356. this._anamorphicRatio = 0.0;
  31357. this._dirtIntensity = 0.0;
  31358. this._shaderSetting = new Vector4();
  31359. this._dirtTileOffset = new Vector4();
  31360. this.clamp = 65472.0;
  31361. this.color = new Color(1.0, 1.0, 1.0, 1.0);
  31362. this.fastMode = false;
  31363. this.dirtTexture = null;
  31364. this._shader = Shader3D.find("PostProcessBloom");
  31365. this._pyramid = new Array(BloomEffect.MAXPYRAMIDSIZE * 2);
  31366. }
  31367. get intensity() {
  31368. return this._intensity;
  31369. }
  31370. set intensity(value) {
  31371. this._intensity = Math.max(value, 0.0);
  31372. }
  31373. get threshold() {
  31374. return this._threshold;
  31375. }
  31376. set threshold(value) {
  31377. this._threshold = Math.max(value, 0.0);
  31378. }
  31379. get softKnee() {
  31380. return this._softKnee;
  31381. }
  31382. set softKnee(value) {
  31383. this._softKnee = Math.min(Math.max(value, 0.0), 1.0);
  31384. }
  31385. get diffusion() {
  31386. return this._diffusion;
  31387. }
  31388. set diffusion(value) {
  31389. this._diffusion = Math.min(Math.max(value, 1), 10);
  31390. }
  31391. get anamorphicRatio() {
  31392. return this._anamorphicRatio;
  31393. }
  31394. set anamorphicRatio(value) {
  31395. this._anamorphicRatio = Math.min(Math.max(value, -1.0), 1.0);
  31396. }
  31397. get dirtIntensity() {
  31398. return this._dirtIntensity;
  31399. }
  31400. set dirtIntensity(value) {
  31401. this._dirtIntensity = Math.max(value, 0.0);
  31402. }
  31403. render(context) {
  31404. var cmd = context.command;
  31405. var viewport = context.camera.viewport;
  31406. this._shaderData.setTexture(BloomEffect.SHADERVALUE_AUTOEXPOSURETEX, Laya.Texture2D.whiteTexture);
  31407. var ratio = this._anamorphicRatio;
  31408. var rw = ratio < 0 ? -ratio : 0;
  31409. var rh = ratio > 0 ? ratio : 0;
  31410. var tw = Math.floor(viewport.width / (2 - rw));
  31411. var th = Math.floor(viewport.height / (2 - rh));
  31412. var s = Math.max(tw, th);
  31413. var logs;
  31414. logs = Math.log2(s) + this._diffusion - 10;
  31415. var logsInt = Math.floor(logs);
  31416. var iterations = Math.min(Math.max(logsInt, 1), BloomEffect.MAXPYRAMIDSIZE);
  31417. var sampleScale = 0.5 + logs - logsInt;
  31418. this._shaderData.setNumber(BloomEffect.SHADERVALUE_SAMPLESCALE, sampleScale);
  31419. var lthresh = Color.gammaToLinearSpace(this.threshold);
  31420. var knee = lthresh * this._softKnee + 1e-5;
  31421. this._shaderThreshold.setValue(lthresh, lthresh - knee, knee * 2, 0.25 / knee);
  31422. this._shaderData.setVector(BloomEffect.SHADERVALUE_THRESHOLD, this._shaderThreshold);
  31423. var lclamp = Color.gammaToLinearSpace(this.clamp);
  31424. this._shaderParams.setValue(lclamp, 0, 0, 0);
  31425. this._shaderData.setVector(BloomEffect.SHADERVALUE_PARAMS, this._shaderParams);
  31426. var qualityOffset = this.fastMode ? 1 : 0;
  31427. var lastDownTexture = context.source;
  31428. for (var i = 0; i < iterations; i++) {
  31429. var downIndex = i * 2;
  31430. var upIndex = downIndex + 1;
  31431. var subShader = i == 0 ? BloomEffect.SUBSHADER_PREFILTER13 + qualityOffset : BloomEffect.SUBSHADER_DOWNSAMPLE13 + qualityOffset;
  31432. var mipDownTexture = RenderTexture.createFromPool(tw, th, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE, Laya.BaseTexture.FILTERMODE_BILINEAR);
  31433. this._pyramid[downIndex] = mipDownTexture;
  31434. if (i !== iterations - 1) {
  31435. var mipUpTexture = RenderTexture.createFromPool(tw, th, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE, Laya.BaseTexture.FILTERMODE_BILINEAR);
  31436. this._pyramid[upIndex] = mipUpTexture;
  31437. }
  31438. cmd.blitScreenTriangle(lastDownTexture, mipDownTexture, this._shader, this._shaderData, subShader);
  31439. lastDownTexture = mipDownTexture;
  31440. tw = Math.max(Math.floor(tw / 2), 1);
  31441. th = Math.max(Math.floor(th / 2), 1);
  31442. }
  31443. var lastUpTexture = this._pyramid[(iterations - 1) * 2];
  31444. for (i = iterations - 2; i >= 0; i--) {
  31445. downIndex = i * 2;
  31446. upIndex = downIndex + 1;
  31447. mipDownTexture = this._pyramid[downIndex];
  31448. mipUpTexture = this._pyramid[upIndex];
  31449. cmd.setShaderDataTexture(this._shaderData, BloomEffect.SHADERVALUE_BLOOMTEX, mipDownTexture);
  31450. cmd.blitScreenTriangle(lastUpTexture, mipUpTexture, this._shader, this._shaderData, BloomEffect.SUBSHADER_UPSAMPLETENT + qualityOffset);
  31451. lastUpTexture = mipUpTexture;
  31452. }
  31453. var linearColor = this._linearColor;
  31454. this.color.toLinear(linearColor);
  31455. var intensity = Math.pow(2, this._intensity / 10.0) - 1.0;
  31456. var shaderSettings = this._shaderSetting;
  31457. this._shaderSetting.setValue(sampleScale, intensity, this._dirtIntensity, iterations);
  31458. var dirtTexture = this.dirtTexture ? this.dirtTexture : Laya.Texture2D.blackTexture;
  31459. var dirtRatio = dirtTexture.width / dirtTexture.height;
  31460. var screenRatio = viewport.width / viewport.height;
  31461. var dirtTileOffset = this._dirtTileOffset;
  31462. if (dirtRatio > screenRatio)
  31463. dirtTileOffset.setValue(screenRatio / dirtRatio, 1.0, (1.0 - dirtTileOffset.x) * 0.5, 0.0);
  31464. else if (dirtRatio < screenRatio)
  31465. dirtTileOffset.setValue(1.0, dirtRatio / screenRatio, 0.0, (1.0 - dirtTileOffset.y) * 0.5);
  31466. var compositeShaderData = context.compositeShaderData;
  31467. if (this.fastMode)
  31468. compositeShaderData.addDefine(PostProcess.SHADERDEFINE_BLOOM_LOW);
  31469. else
  31470. compositeShaderData.addDefine(PostProcess.SHADERDEFINE_BLOOM);
  31471. this._bloomTextureTexelSize.setValue(1.0 / lastUpTexture.width, 1.0 / lastUpTexture.height, lastUpTexture.width, lastUpTexture.height);
  31472. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_DIRTTILEOFFSET, dirtTileOffset);
  31473. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_SETTINGS, shaderSettings);
  31474. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_COLOR, new Vector4(linearColor.r, linearColor.g, linearColor.b, linearColor.a));
  31475. compositeShaderData.setTexture(PostProcess.SHADERVALUE_BLOOM_DIRTTEX, dirtTexture);
  31476. compositeShaderData.setTexture(PostProcess.SHADERVALUE_BLOOMTEX, lastUpTexture);
  31477. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOMTEX_TEXELSIZE, this._bloomTextureTexelSize);
  31478. for (i = 0; i < iterations; i++) {
  31479. downIndex = i * 2;
  31480. upIndex = downIndex + 1;
  31481. RenderTexture.recoverToPool(this._pyramid[downIndex]);
  31482. (i !== 0 && i !== iterations - 1) && (RenderTexture.recoverToPool(this._pyramid[upIndex]));
  31483. }
  31484. context.deferredReleaseTextures.push(lastUpTexture);
  31485. }
  31486. }
  31487. BloomEffect.SHADERVALUE_MAINTEX = Shader3D.propertyNameToID("u_MainTex");
  31488. BloomEffect.SHADERVALUE_AUTOEXPOSURETEX = Shader3D.propertyNameToID("u_AutoExposureTex");
  31489. BloomEffect.SHADERVALUE_SAMPLESCALE = Shader3D.propertyNameToID("u_SampleScale");
  31490. BloomEffect.SHADERVALUE_THRESHOLD = Shader3D.propertyNameToID("u_Threshold");
  31491. BloomEffect.SHADERVALUE_PARAMS = Shader3D.propertyNameToID("u_Params");
  31492. BloomEffect.SHADERVALUE_BLOOMTEX = Shader3D.propertyNameToID("u_BloomTex");
  31493. BloomEffect.SUBSHADER_PREFILTER13 = 0;
  31494. BloomEffect.SUBSHADER_PREFILTER4 = 1;
  31495. BloomEffect.SUBSHADER_DOWNSAMPLE13 = 2;
  31496. BloomEffect.SUBSHADER_DOWNSAMPLE4 = 3;
  31497. BloomEffect.SUBSHADER_UPSAMPLETENT = 4;
  31498. BloomEffect.SUBSHADER_UPSAMPLEBOX = 5;
  31499. BloomEffect.MAXPYRAMIDSIZE = 16;
  31500. class SceneManager {
  31501. constructor() {
  31502. }
  31503. }
  31504. class RandX {
  31505. constructor(seed) {
  31506. if (!(seed instanceof Array) || seed.length !== 4)
  31507. throw new Error('Rand:Seed must be an array with 4 numbers');
  31508. this._state0U = seed[0] | 0;
  31509. this._state0L = seed[1] | 0;
  31510. this._state1U = seed[2] | 0;
  31511. this._state1L = seed[3] | 0;
  31512. }
  31513. randomint() {
  31514. var s1U = this._state0U, s1L = this._state0L;
  31515. var s0U = this._state1U, s0L = this._state1L;
  31516. var sumL = (s0L >>> 0) + (s1L >>> 0);
  31517. var resU = (s0U + s1U + (sumL / 2 >>> 31)) >>> 0;
  31518. var resL = sumL >>> 0;
  31519. this._state0U = s0U;
  31520. this._state0L = s0L;
  31521. var t1U = 0, t1L = 0;
  31522. var t2U = 0, t2L = 0;
  31523. var a1 = 23;
  31524. var m1 = 0xFFFFFFFF << (32 - a1);
  31525. t1U = (s1U << a1) | ((s1L & m1) >>> (32 - a1));
  31526. t1L = s1L << a1;
  31527. s1U = s1U ^ t1U;
  31528. s1L = s1L ^ t1L;
  31529. t1U = s1U ^ s0U;
  31530. t1L = s1L ^ s0L;
  31531. var a2 = 18;
  31532. var m2 = 0xFFFFFFFF >>> (32 - a2);
  31533. t2U = s1U >>> a2;
  31534. t2L = (s1L >>> a2) | ((s1U & m2) << (32 - a2));
  31535. t1U = t1U ^ t2U;
  31536. t1L = t1L ^ t2L;
  31537. var a3 = 5;
  31538. var m3 = 0xFFFFFFFF >>> (32 - a3);
  31539. t2U = s0U >>> a3;
  31540. t2L = (s0L >>> a3) | ((s0U & m3) << (32 - a3));
  31541. t1U = t1U ^ t2U;
  31542. t1L = t1L ^ t2L;
  31543. this._state1U = t1U;
  31544. this._state1L = t1L;
  31545. return [resU, resL];
  31546. }
  31547. random() {
  31548. var t2 = this.randomint();
  31549. var t2U = t2[0];
  31550. var t2L = t2[1];
  31551. var eU = 0x3FF << (52 - 32);
  31552. var eL = 0;
  31553. var a1 = 12;
  31554. var m1 = 0xFFFFFFFF >>> (32 - a1);
  31555. var sU = t2U >>> a1;
  31556. var sL = (t2L >>> a1) | ((t2U & m1) << (32 - a1));
  31557. var xU = eU | sU;
  31558. var xL = eL | sL;
  31559. RandX._CONVERTION_BUFFER.setUint32(0, xU, false);
  31560. RandX._CONVERTION_BUFFER.setUint32(4, xL, false);
  31561. var d = RandX._CONVERTION_BUFFER.getFloat64(0, false);
  31562. return d - 1;
  31563. }
  31564. }
  31565. RandX._CONVERTION_BUFFER = new DataView(new ArrayBuffer(8));
  31566. RandX.defaultRand = new RandX([0, Date.now() / 65536, 0, Date.now() % 65536]);
  31567. class Constraint3D {
  31568. constructor() {
  31569. }
  31570. }
  31571. class ConstraintComponent extends Laya.Component {
  31572. constructor() {
  31573. super();
  31574. this._feedbackEnabled = false;
  31575. }
  31576. get enabled() {
  31577. return super.enabled;
  31578. }
  31579. set enabled(value) {
  31580. this._nativeConstraint.IsEnabled = value;
  31581. super.enabled = value;
  31582. }
  31583. get breakingImpulseThreshold() {
  31584. return this._breakingImpulseThreshold;
  31585. }
  31586. set breakingImpulseThreshold(value) {
  31587. this._nativeConstraint.BreakingImpulseThreshold = value;
  31588. this._breakingImpulseThreshold = value;
  31589. }
  31590. get appliedImpulse() {
  31591. if (!this._feedbackEnabled) {
  31592. this._nativeConstraint.EnableFeedback(true);
  31593. this._feedbackEnabled = true;
  31594. }
  31595. return this._nativeConstraint.AppliedImpulse;
  31596. }
  31597. get connectedBody() {
  31598. return this._connectedBody;
  31599. }
  31600. set connectedBody(value) {
  31601. this._connectedBody = value;
  31602. }
  31603. _onDestroy() {
  31604. var physics3D = Physics3D._physics3D;
  31605. physics3D.destroy(this._nativeConstraint);
  31606. this._nativeConstraint = null;
  31607. }
  31608. }
  31609. class Point2PointConstraint {
  31610. constructor() {
  31611. this._pivotInA = new Vector3();
  31612. this._pivotInB = new Vector3();
  31613. }
  31614. get pivotInA() {
  31615. return this._pivotInA;
  31616. }
  31617. set pivotInA(value) {
  31618. this._pivotInA = value;
  31619. }
  31620. get pivotInB() {
  31621. return this._pivotInB;
  31622. }
  31623. set pivotInB(value) {
  31624. this._pivotInB = value;
  31625. }
  31626. get damping() {
  31627. return this._damping;
  31628. }
  31629. set damping(value) {
  31630. this._damping = value;
  31631. }
  31632. get impulseClamp() {
  31633. return this._impulseClamp;
  31634. }
  31635. set impulseClamp(value) {
  31636. this._impulseClamp = value;
  31637. }
  31638. get tau() {
  31639. return this._tau;
  31640. }
  31641. set tau(value) {
  31642. this._tau = value;
  31643. }
  31644. }
  31645. class HeightfieldColliderShape {
  31646. constructor() {
  31647. }
  31648. }
  31649. class TextMesh {
  31650. get text() {
  31651. return this._text;
  31652. }
  31653. set text(value) {
  31654. this._text = value;
  31655. }
  31656. get fontSize() {
  31657. return this._fontSize;
  31658. }
  31659. set fontSize(value) {
  31660. this._fontSize = value;
  31661. }
  31662. get color() {
  31663. return this._color;
  31664. }
  31665. set color(value) {
  31666. this._color = value;
  31667. }
  31668. constructor() {
  31669. }
  31670. _createVertexBuffer(charCount) {
  31671. }
  31672. _resizeVertexBuffer(charCount) {
  31673. }
  31674. _addChar() {
  31675. }
  31676. }
  31677. class Size {
  31678. constructor(width, height) {
  31679. this._width = 0;
  31680. this._height = 0;
  31681. this._width = width;
  31682. this._height = height;
  31683. }
  31684. static get fullScreen() {
  31685. return new Size(-1, -1);
  31686. }
  31687. get width() {
  31688. if (this._width === -1)
  31689. return RenderContext3D.clientWidth;
  31690. return this._width;
  31691. }
  31692. get height() {
  31693. if (this._height === -1)
  31694. return RenderContext3D.clientHeight;
  31695. return this._height;
  31696. }
  31697. }
  31698. exports.AlternateLightQueue = AlternateLightQueue;
  31699. exports.AnimationClip = AnimationClip;
  31700. exports.AnimationClipParser03 = AnimationClipParser03;
  31701. exports.AnimationClipParser04 = AnimationClipParser04;
  31702. exports.AnimationEvent = AnimationEvent;
  31703. exports.AnimationNode = AnimationNode;
  31704. exports.AnimationTransform3D = AnimationTransform3D;
  31705. exports.Animator = Animator;
  31706. exports.AnimatorControllerLayer = AnimatorControllerLayer;
  31707. exports.AnimatorPlayState = AnimatorPlayState;
  31708. exports.AnimatorState = AnimatorState;
  31709. exports.AnimatorStateScript = AnimatorStateScript;
  31710. exports.Avatar = Avatar;
  31711. exports.BaseCamera = BaseCamera;
  31712. exports.BaseMaterial = BaseMaterial;
  31713. exports.BaseRender = BaseRender;
  31714. exports.BaseShape = BaseShape;
  31715. exports.BatchMark = BatchMark;
  31716. exports.BlinnPhongMaterial = BlinnPhongMaterial;
  31717. exports.BlitScreenQuadCMD = BlitScreenQuadCMD;
  31718. exports.BloomEffect = BloomEffect;
  31719. exports.BoundBox = BoundBox;
  31720. exports.BoundFrustum = BoundFrustum;
  31721. exports.BoundSphere = BoundSphere;
  31722. exports.Bounds = Bounds;
  31723. exports.BoundsOctree = BoundsOctree;
  31724. exports.BoundsOctreeNode = BoundsOctreeNode;
  31725. exports.BoxColliderShape = BoxColliderShape;
  31726. exports.BoxShape = BoxShape;
  31727. exports.BufferState = BufferState;
  31728. exports.Burst = Burst;
  31729. exports.Camera = Camera;
  31730. exports.CapsuleColliderShape = CapsuleColliderShape;
  31731. exports.CastShadowList = CastShadowList;
  31732. exports.CharacterController = CharacterController;
  31733. exports.CircleShape = CircleShape;
  31734. exports.Cluster = Cluster;
  31735. exports.ColliderShape = ColliderShape;
  31736. exports.Collision = Collision;
  31737. exports.CollisionTool = CollisionTool;
  31738. exports.CollisionUtils = CollisionUtils;
  31739. exports.Color = Color;
  31740. exports.ColorOverLifetime = ColorOverLifetime;
  31741. exports.Command = Command;
  31742. exports.CommandBuffer = CommandBuffer;
  31743. exports.CompoundColliderShape = CompoundColliderShape;
  31744. exports.ConchQuaternion = ConchQuaternion;
  31745. exports.ConchVector3 = ConchVector3;
  31746. exports.ConchVector4 = ConchVector4;
  31747. exports.ConeColliderShape = ConeColliderShape;
  31748. exports.ConeShape = ConeShape;
  31749. exports.Config3D = Config3D;
  31750. exports.Constraint3D = Constraint3D;
  31751. exports.ConstraintComponent = ConstraintComponent;
  31752. exports.ContactPoint = ContactPoint;
  31753. exports.ContainmentType = ContainmentType;
  31754. exports.CylinderColliderShape = CylinderColliderShape;
  31755. exports.DefineDatas = DefineDatas;
  31756. exports.DirectionLight = DirectionLight;
  31757. exports.DirectionLightQueue = DirectionLightQueue;
  31758. exports.DynamicBatchManager = DynamicBatchManager;
  31759. exports.EffectMaterial = EffectMaterial;
  31760. exports.Emission = Emission;
  31761. exports.ExtendTerrainMaterial = ExtendTerrainMaterial;
  31762. exports.FloatKeyframe = FloatKeyframe;
  31763. exports.FrameOverTime = FrameOverTime;
  31764. exports.FrustumCulling = FrustumCulling;
  31765. exports.GeometryElement = GeometryElement;
  31766. exports.Gradient = Gradient;
  31767. exports.GradientAngularVelocity = GradientAngularVelocity;
  31768. exports.GradientColor = GradientColor;
  31769. exports.GradientDataInt = GradientDataInt;
  31770. exports.GradientDataNumber = GradientDataNumber;
  31771. exports.GradientDataVector2 = GradientDataVector2;
  31772. exports.GradientMode = GradientMode;
  31773. exports.GradientSize = GradientSize;
  31774. exports.GradientVelocity = GradientVelocity;
  31775. exports.HalfFloatUtils = HalfFloatUtils;
  31776. exports.HeightMap = HeightMap;
  31777. exports.HeightfieldColliderShape = HeightfieldColliderShape;
  31778. exports.HemisphereShape = HemisphereShape;
  31779. exports.HitResult = HitResult;
  31780. exports.ILaya3D = ILaya3D;
  31781. exports.IndexBuffer3D = IndexBuffer3D;
  31782. exports.Input3D = Input3D;
  31783. exports.Keyframe = Keyframe;
  31784. exports.KeyframeNode = KeyframeNode;
  31785. exports.KeyframeNodeList = KeyframeNodeList;
  31786. exports.KeyframeNodeOwner = KeyframeNodeOwner;
  31787. exports.Laya3D = Laya3D;
  31788. exports.LightQueue = LightQueue;
  31789. exports.LightSprite = LightSprite;
  31790. exports.LoadModelV04 = LoadModelV04;
  31791. exports.LoadModelV05 = LoadModelV05;
  31792. exports.MathUtils3D = MathUtils3D;
  31793. exports.Matrix3x3 = Matrix3x3;
  31794. exports.Matrix4x4 = Matrix4x4;
  31795. exports.Mesh = Mesh;
  31796. exports.MeshColliderShape = MeshColliderShape;
  31797. exports.MeshFilter = MeshFilter;
  31798. exports.MeshReader = MeshReader;
  31799. exports.MeshRenderDynamicBatchManager = MeshRenderDynamicBatchManager;
  31800. exports.MeshRenderStaticBatchManager = MeshRenderStaticBatchManager;
  31801. exports.MeshRenderer = MeshRenderer;
  31802. exports.MeshSprite3D = MeshSprite3D;
  31803. exports.MeshSprite3DShaderDeclaration = MeshSprite3DShaderDeclaration;
  31804. exports.MeshTerrainSprite3D = MeshTerrainSprite3D;
  31805. exports.MouseTouch = MouseTouch;
  31806. exports.OctreeMotionList = OctreeMotionList;
  31807. exports.PBRSpecularMaterial = PBRSpecularMaterial;
  31808. exports.PBRStandardMaterial = PBRStandardMaterial;
  31809. exports.ParallelSplitShadowMap = ParallelSplitShadowMap;
  31810. exports.Physics3D = Physics3D;
  31811. exports.Physics3DUtils = Physics3DUtils;
  31812. exports.PhysicsCollider = PhysicsCollider;
  31813. exports.PhysicsComponent = PhysicsComponent;
  31814. exports.PhysicsSettings = PhysicsSettings;
  31815. exports.PhysicsSimulation = PhysicsSimulation;
  31816. exports.PhysicsTriggerComponent = PhysicsTriggerComponent;
  31817. exports.PhysicsUpdateList = PhysicsUpdateList;
  31818. exports.Picker = Picker;
  31819. exports.PixelLineData = PixelLineData;
  31820. exports.PixelLineFilter = PixelLineFilter;
  31821. exports.PixelLineMaterial = PixelLineMaterial;
  31822. exports.PixelLineRenderer = PixelLineRenderer;
  31823. exports.PixelLineSprite3D = PixelLineSprite3D;
  31824. exports.PixelLineVertex = PixelLineVertex;
  31825. exports.Plane = Plane;
  31826. exports.Point2PointConstraint = Point2PointConstraint;
  31827. exports.PointLight = PointLight;
  31828. exports.PostProcess = PostProcess;
  31829. exports.PostProcessEffect = PostProcessEffect;
  31830. exports.PostProcessRenderContext = PostProcessRenderContext;
  31831. exports.PrimitiveMesh = PrimitiveMesh;
  31832. exports.Quaternion = Quaternion;
  31833. exports.QuaternionKeyframe = QuaternionKeyframe;
  31834. exports.Rand = Rand;
  31835. exports.RandX = RandX;
  31836. exports.Ray = Ray;
  31837. exports.RenderContext3D = RenderContext3D;
  31838. exports.RenderElement = RenderElement;
  31839. exports.RenderQueue = RenderQueue;
  31840. exports.RenderState = RenderState;
  31841. exports.RenderTexture = RenderTexture;
  31842. exports.RenderableSprite3D = RenderableSprite3D;
  31843. exports.Rigidbody3D = Rigidbody3D;
  31844. exports.RotationOverLifetime = RotationOverLifetime;
  31845. exports.Scene3D = Scene3D;
  31846. exports.Scene3DShaderDeclaration = Scene3DShaderDeclaration;
  31847. exports.Scene3DUtils = Scene3DUtils;
  31848. exports.SceneManager = SceneManager;
  31849. exports.ScreenQuad = ScreenQuad;
  31850. exports.ScreenTriangle = ScreenTriangle;
  31851. exports.Script3D = Script3D;
  31852. exports.SetRenderTargetCMD = SetRenderTargetCMD;
  31853. exports.SetShaderDataTextureCMD = SetShaderDataTextureCMD;
  31854. exports.Shader3D = Shader3D;
  31855. exports.ShaderData = ShaderData;
  31856. exports.ShaderDefine = ShaderDefine;
  31857. exports.ShaderInit3D = ShaderInit3D;
  31858. exports.ShaderInstance = ShaderInstance;
  31859. exports.ShaderPass = ShaderPass;
  31860. exports.ShaderVariable = ShaderVariable;
  31861. exports.ShapeUtils = ShapeUtils;
  31862. exports.ShuriKenParticle3D = ShuriKenParticle3D;
  31863. exports.ShuriKenParticle3DShaderDeclaration = ShuriKenParticle3DShaderDeclaration;
  31864. exports.ShurikenParticleData = ShurikenParticleData;
  31865. exports.ShurikenParticleMaterial = ShurikenParticleMaterial;
  31866. exports.ShurikenParticleRenderer = ShurikenParticleRenderer;
  31867. exports.ShurikenParticleSystem = ShurikenParticleSystem;
  31868. exports.SimpleSingletonList = SimpleSingletonList;
  31869. exports.SingletonList = SingletonList;
  31870. exports.Size = Size;
  31871. exports.SizeOverLifetime = SizeOverLifetime;
  31872. exports.SkinnedMeshRenderer = SkinnedMeshRenderer;
  31873. exports.SkinnedMeshSprite3D = SkinnedMeshSprite3D;
  31874. exports.SkinnedMeshSprite3DShaderDeclaration = SkinnedMeshSprite3DShaderDeclaration;
  31875. exports.SkyBox = SkyBox;
  31876. exports.SkyBoxMaterial = SkyBoxMaterial;
  31877. exports.SkyDome = SkyDome;
  31878. exports.SkyMesh = SkyMesh;
  31879. exports.SkyProceduralMaterial = SkyProceduralMaterial;
  31880. exports.SkyRenderer = SkyRenderer;
  31881. exports.SphereColliderShape = SphereColliderShape;
  31882. exports.SphereShape = SphereShape;
  31883. exports.SpotLight = SpotLight;
  31884. exports.Sprite3D = Sprite3D;
  31885. exports.StartFrame = StartFrame;
  31886. exports.StaticBatchManager = StaticBatchManager;
  31887. exports.StaticPlaneColliderShape = StaticPlaneColliderShape;
  31888. exports.SubMesh = SubMesh;
  31889. exports.SubMeshDynamicBatch = SubMeshDynamicBatch;
  31890. exports.SubMeshInstanceBatch = SubMeshInstanceBatch;
  31891. exports.SubMeshRenderElement = SubMeshRenderElement;
  31892. exports.SubMeshStaticBatch = SubMeshStaticBatch;
  31893. exports.SubShader = SubShader;
  31894. exports.SystemUtils = SystemUtils;
  31895. exports.TextMesh = TextMesh;
  31896. exports.TextureCube = TextureCube;
  31897. exports.TextureGenerator = TextureGenerator;
  31898. exports.TextureMode = TextureMode;
  31899. exports.TextureSheetAnimation = TextureSheetAnimation;
  31900. exports.Touch = Touch;
  31901. exports.TrailFilter = TrailFilter;
  31902. exports.TrailGeometry = TrailGeometry;
  31903. exports.TrailMaterial = TrailMaterial;
  31904. exports.TrailRenderer = TrailRenderer;
  31905. exports.TrailSprite3D = TrailSprite3D;
  31906. exports.Transform3D = Transform3D;
  31907. exports.UnlitMaterial = UnlitMaterial;
  31908. exports.Utils3D = Utils3D;
  31909. exports.Vector2 = Vector2;
  31910. exports.Vector3 = Vector3;
  31911. exports.Vector3Keyframe = Vector3Keyframe;
  31912. exports.Vector4 = Vector4;
  31913. exports.VelocityOverLifetime = VelocityOverLifetime;
  31914. exports.VertexBuffer3D = VertexBuffer3D;
  31915. exports.VertexDeclaration = VertexDeclaration;
  31916. exports.VertexElement = VertexElement;
  31917. exports.VertexElementFormat = VertexElementFormat;
  31918. exports.VertexMesh = VertexMesh;
  31919. exports.VertexPositionTerrain = VertexPositionTerrain;
  31920. exports.VertexPositionTexture0 = VertexPositionTexture0;
  31921. exports.VertexShuriKenParticle = VertexShuriKenParticle;
  31922. exports.VertexShurikenParticleBillboard = VertexShurikenParticleBillboard;
  31923. exports.VertexShurikenParticleMesh = VertexShurikenParticleMesh;
  31924. exports.VertexTrail = VertexTrail;
  31925. exports.Viewport = Viewport;
  31926. exports.WaterPrimaryMaterial = WaterPrimaryMaterial;
  31927. }(window.Laya = window.Laya|| {}, Laya));