123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328 |
- var __reflect = (this && this.__reflect) || function (p, c, t) {
- p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
- };
- var __extends = this && this.__extends || function __extends(t, e) {
- function r() {
- this.constructor = t;
- }
- for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]);
- r.prototype = e.prototype, t.prototype = new r();
- };
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- function getOption(key) {
- if (window.location) {
- var search = location.search;
- if (search == "") {
- return "";
- }
- search = search.slice(1);
- var searchArr = search.split("&");
- var length_1 = searchArr.length;
- for (var i = 0; i < length_1; i++) {
- var str = searchArr[i];
- var arr = str.split("=");
- if (arr[0] == key) {
- return arr[1];
- }
- }
- }
- return "";
- }
- web.getOption = getOption;
- egret.getOption = getOption;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var WebExternalInterface = (function () {
- function WebExternalInterface() {
- }
- /**
- * @private
- * @param functionName
- * @param value
- */
- WebExternalInterface.call = function (functionName, value) {
- };
- /**
- * @private
- * @param functionName
- * @param listener
- */
- WebExternalInterface.addCallback = function (functionName, listener) {
- };
- return WebExternalInterface;
- }());
- web.WebExternalInterface = WebExternalInterface;
- __reflect(WebExternalInterface.prototype, "egret.web.WebExternalInterface", ["egret.ExternalInterface"]);
- var ua = navigator.userAgent.toLowerCase();
- if (ua.indexOf("egretnative") < 0) {
- egret.ExternalInterface = WebExternalInterface;
- }
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- (function (egret) {
- var web;
- (function (web) {
- var callBackDic = {};
- /**
- * @private
- */
- var NativeExternalInterface = (function () {
- function NativeExternalInterface() {
- }
- NativeExternalInterface.call = function (functionName, value) {
- var data = {};
- data.functionName = functionName;
- data.value = value;
- egret_native.sendInfoToPlugin(JSON.stringify(data));
- };
- NativeExternalInterface.addCallback = function (functionName, listener) {
- callBackDic[functionName] = listener;
- };
- return NativeExternalInterface;
- }());
- web.NativeExternalInterface = NativeExternalInterface;
- __reflect(NativeExternalInterface.prototype, "egret.web.NativeExternalInterface", ["egret.ExternalInterface"]);
- /**
- * @private
- * @param info
- */
- function onReceivedPluginInfo(info) {
- var data = JSON.parse(info);
- var functionName = data.functionName;
- var listener = callBackDic[functionName];
- if (listener) {
- var value = data.value;
- listener.call(null, value);
- }
- else {
- egret.$warn(1050, functionName);
- }
- }
- var ua = navigator.userAgent.toLowerCase();
- if (ua.indexOf("egretnative") >= 0) {
- egret.ExternalInterface = NativeExternalInterface;
- egret_native.receivedPluginInfo = onReceivedPluginInfo;
- }
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- (function (egret) {
- var web;
- (function (web) {
- var callBackDic = {};
- /**
- * @private
- */
- var WebViewExternalInterface = (function () {
- function WebViewExternalInterface() {
- }
- WebViewExternalInterface.call = function (functionName, value) {
- __global.ExternalInterface.call(functionName, value);
- };
- WebViewExternalInterface.addCallback = function (functionName, listener) {
- callBackDic[functionName] = listener;
- };
- WebViewExternalInterface.invokeCallback = function (functionName, value) {
- var listener = callBackDic[functionName];
- if (listener) {
- listener.call(null, value);
- }
- else {
- egret.$warn(1050, functionName);
- }
- };
- return WebViewExternalInterface;
- }());
- web.WebViewExternalInterface = WebViewExternalInterface;
- __reflect(WebViewExternalInterface.prototype, "egret.web.WebViewExternalInterface", ["egret.ExternalInterface"]);
- var ua = navigator.userAgent.toLowerCase();
- if (ua.indexOf("egretwebview") >= 0) {
- egret.ExternalInterface = WebViewExternalInterface;
- }
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- * @inheritDoc
- */
- var HtmlSound = (function (_super) {
- __extends(HtmlSound, _super);
- /**
- * @private
- * @inheritDoc
- */
- function HtmlSound() {
- var _this = _super.call(this) || this;
- /**
- * @private
- */
- _this.loaded = false;
- return _this;
- }
- Object.defineProperty(HtmlSound.prototype, "length", {
- get: function () {
- if (this.originAudio) {
- return this.originAudio.duration;
- }
- throw new Error("sound not loaded!");
- //return 0;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * @inheritDoc
- */
- HtmlSound.prototype.load = function (url) {
- var self = this;
- this.url = url;
- if (true && !url) {
- egret.$error(3002);
- }
- var audio = new Audio(url);
- audio.addEventListener("canplaythrough", onAudioLoaded);
- audio.addEventListener("error", onAudioError);
- var ua = navigator.userAgent.toLowerCase();
- if (ua.indexOf("firefox") >= 0) {
- audio.autoplay = !0;
- audio.muted = true;
- }
- if (ua.indexOf("edge") >= 0) {
- document.body.appendChild(audio);
- }
- audio.load();
- this.originAudio = audio;
- if (HtmlSound.clearAudios[this.url]) {
- delete HtmlSound.clearAudios[this.url];
- }
- function onAudioLoaded() {
- HtmlSound.$recycle(this.url, audio);
- removeListeners();
- if (ua.indexOf("firefox") >= 0) {
- audio.pause();
- audio.muted = false;
- }
- self.loaded = true;
- self.dispatchEventWith(egret.Event.COMPLETE);
- }
- function onAudioError() {
- removeListeners();
- self.dispatchEventWith(egret.IOErrorEvent.IO_ERROR);
- }
- function removeListeners() {
- audio.removeEventListener("canplaythrough", onAudioLoaded);
- audio.removeEventListener("error", onAudioError);
- if (ua.indexOf("edge") >= 0) {
- document.body.removeChild(audio);
- }
- }
- };
- /**
- * @inheritDoc
- */
- HtmlSound.prototype.play = function (startTime, loops) {
- startTime = +startTime || 0;
- loops = +loops || 0;
- if (true && this.loaded == false) {
- egret.$error(1049);
- }
- var audio = HtmlSound.$pop(this.url);
- if (audio == null) {
- audio = this.originAudio.cloneNode();
- }
- else {
- //audio.load();
- }
- audio.autoplay = true;
- var channel = new web.HtmlSoundChannel(audio);
- channel.$url = this.url;
- channel.$loops = loops;
- channel.$startTime = startTime;
- channel.$play();
- egret.sys.$pushSoundChannel(channel);
- return channel;
- };
- /**
- * @inheritDoc
- */
- HtmlSound.prototype.close = function () {
- if (this.loaded == false && this.originAudio)
- this.originAudio.src = "";
- if (this.originAudio)
- this.originAudio = null;
- HtmlSound.$clear(this.url);
- };
- HtmlSound.$clear = function (url) {
- HtmlSound.clearAudios[url] = true;
- var array = HtmlSound.audios[url];
- if (array) {
- array.length = 0;
- }
- };
- HtmlSound.$pop = function (url) {
- var array = HtmlSound.audios[url];
- if (array && array.length > 0) {
- return array.pop();
- }
- return null;
- };
- HtmlSound.$recycle = function (url, audio) {
- if (HtmlSound.clearAudios[url]) {
- return;
- }
- var array = HtmlSound.audios[url];
- if (HtmlSound.audios[url] == null) {
- array = HtmlSound.audios[url] = [];
- }
- array.push(audio);
- };
- /**
- * Background music
- * @version Egret 2.4
- * @platform Web,Native
- * @language en_US
- */
- /**
- * 背景音乐
- * @version Egret 2.4
- * @platform Web,Native
- * @language zh_CN
- */
- HtmlSound.MUSIC = "music";
- /**
- * EFFECT
- * @version Egret 2.4
- * @platform Web,Native
- * @language en_US
- */
- /**
- * 音效
- * @version Egret 2.4
- * @platform Web,Native
- * @language zh_CN
- */
- HtmlSound.EFFECT = "effect";
- /**
- * @private
- */
- HtmlSound.audios = {};
- HtmlSound.clearAudios = {};
- return HtmlSound;
- }(egret.EventDispatcher));
- web.HtmlSound = HtmlSound;
- __reflect(HtmlSound.prototype, "egret.web.HtmlSound", ["egret.Sound"]);
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- * @inheritDoc
- */
- var HtmlSoundChannel = (function (_super) {
- __extends(HtmlSoundChannel, _super);
- /**
- * @private
- */
- function HtmlSoundChannel(audio) {
- var _this = _super.call(this) || this;
- /**
- * @private
- */
- _this.$startTime = 0;
- /**
- * @private
- */
- _this.audio = null;
- //声音是否已经播放完成
- _this.isStopped = false;
- _this.canPlay = function () {
- _this.audio.removeEventListener("canplay", _this.canPlay);
- try {
- _this.audio.currentTime = _this.$startTime;
- }
- catch (e) {
- }
- finally {
- _this.audio.play();
- }
- };
- /**
- * @private
- */
- _this.onPlayEnd = function () {
- if (_this.$loops == 1) {
- _this.stop();
- _this.dispatchEventWith(egret.Event.SOUND_COMPLETE);
- return;
- }
- if (_this.$loops > 0) {
- _this.$loops--;
- }
- /////////////
- //this.audio.load();
- _this.$play();
- };
- /**
- * @private
- */
- _this._volume = 1;
- audio.addEventListener("ended", _this.onPlayEnd);
- _this.audio = audio;
- return _this;
- }
- HtmlSoundChannel.prototype.$play = function () {
- if (this.isStopped) {
- egret.$error(1036);
- return;
- }
- try {
- //this.audio.pause();
- this.audio.volume = this._volume;
- this.audio.currentTime = this.$startTime;
- }
- catch (e) {
- this.audio.addEventListener("canplay", this.canPlay);
- return;
- }
- this.audio.play();
- };
- /**
- * @private
- * @inheritDoc
- */
- HtmlSoundChannel.prototype.stop = function () {
- if (!this.audio)
- return;
- if (!this.isStopped) {
- egret.sys.$popSoundChannel(this);
- }
- this.isStopped = true;
- var audio = this.audio;
- audio.removeEventListener("ended", this.onPlayEnd);
- audio.removeEventListener("canplay", this.canPlay);
- audio.volume = 0;
- this._volume = 0;
- this.audio = null;
- var url = this.$url;
- //延迟一定时间再停止,规避chrome报错
- window.setTimeout(function () {
- audio.pause();
- web.HtmlSound.$recycle(url, audio);
- }, 200);
- };
- Object.defineProperty(HtmlSoundChannel.prototype, "volume", {
- /**
- * @private
- * @inheritDoc
- */
- get: function () {
- return this._volume;
- },
- /**
- * @inheritDoc
- */
- set: function (value) {
- if (this.isStopped) {
- egret.$error(1036);
- return;
- }
- this._volume = value;
- if (!this.audio)
- return;
- this.audio.volume = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(HtmlSoundChannel.prototype, "position", {
- /**
- * @private
- * @inheritDoc
- */
- get: function () {
- if (!this.audio)
- return 0;
- return this.audio.currentTime;
- },
- enumerable: true,
- configurable: true
- });
- return HtmlSoundChannel;
- }(egret.EventDispatcher));
- web.HtmlSoundChannel = HtmlSoundChannel;
- __reflect(HtmlSoundChannel.prototype, "egret.web.HtmlSoundChannel", ["egret.SoundChannel", "egret.IEventDispatcher"]);
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var WebAudioDecode = (function () {
- function WebAudioDecode() {
- }
- /**
- * @private
- *
- */
- WebAudioDecode.decodeAudios = function () {
- if (WebAudioDecode.decodeArr.length <= 0) {
- return;
- }
- if (WebAudioDecode.isDecoding) {
- return;
- }
- WebAudioDecode.isDecoding = true;
- var decodeInfo = WebAudioDecode.decodeArr.shift();
- WebAudioDecode.ctx.decodeAudioData(decodeInfo["buffer"], function (audioBuffer) {
- decodeInfo["self"].audioBuffer = audioBuffer;
- if (decodeInfo["success"]) {
- decodeInfo["success"]();
- }
- WebAudioDecode.isDecoding = false;
- WebAudioDecode.decodeAudios();
- }, function () {
- alert("sound decode error: " + decodeInfo["url"] + "!\nsee http://edn.egret.com/cn/docs/page/156");
- if (decodeInfo["fail"]) {
- decodeInfo["fail"]();
- }
- WebAudioDecode.isDecoding = false;
- WebAudioDecode.decodeAudios();
- });
- };
- /**
- * @private
- */
- WebAudioDecode.decodeArr = [];
- /**
- * @private
- */
- WebAudioDecode.isDecoding = false;
- return WebAudioDecode;
- }());
- web.WebAudioDecode = WebAudioDecode;
- __reflect(WebAudioDecode.prototype, "egret.web.WebAudioDecode");
- /**
- * @private
- * @inheritDoc
- */
- var WebAudioSound = (function (_super) {
- __extends(WebAudioSound, _super);
- /**
- * @private
- * @inheritDoc
- */
- function WebAudioSound() {
- var _this = _super.call(this) || this;
- /**
- * @private
- */
- _this.loaded = false;
- return _this;
- }
- Object.defineProperty(WebAudioSound.prototype, "length", {
- get: function () {
- if (this.audioBuffer) {
- return this.audioBuffer.duration;
- }
- throw new Error("sound not loaded!");
- //return 0;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * @inheritDoc
- */
- WebAudioSound.prototype.load = function (url) {
- var self = this;
- this.url = url;
- if (true && !url) {
- egret.$error(3002);
- }
- var request = new XMLHttpRequest();
- request.open("GET", url, true);
- request.responseType = "arraybuffer";
- request.onreadystatechange = function () {
- if (request.readyState == 4) {
- var ioError = (request.status >= 400 || request.status == 0);
- if (ioError) {
- self.dispatchEventWith(egret.IOErrorEvent.IO_ERROR);
- }
- else {
- WebAudioDecode.decodeArr.push({
- "buffer": request.response,
- "success": onAudioLoaded,
- "fail": onAudioError,
- "self": self,
- "url": self.url
- });
- WebAudioDecode.decodeAudios();
- }
- }
- };
- request.send();
- function onAudioLoaded() {
- self.loaded = true;
- self.dispatchEventWith(egret.Event.COMPLETE);
- }
- function onAudioError() {
- self.dispatchEventWith(egret.IOErrorEvent.IO_ERROR);
- }
- };
- /**
- * @inheritDoc
- */
- WebAudioSound.prototype.play = function (startTime, loops) {
- startTime = +startTime || 0;
- loops = +loops || 0;
- if (true && this.loaded == false) {
- egret.$error(1049);
- }
- var channel = new web.WebAudioSoundChannel();
- channel.$url = this.url;
- channel.$loops = loops;
- channel.$audioBuffer = this.audioBuffer;
- channel.$startTime = startTime;
- channel.$play();
- egret.sys.$pushSoundChannel(channel);
- return channel;
- };
- /**
- * @inheritDoc
- */
- WebAudioSound.prototype.close = function () {
- };
- /**
- * Background music
- * @version Egret 2.4
- * @platform Web,Native
- * @language en_US
- */
- /**
- * 背景音乐
- * @version Egret 2.4
- * @platform Web,Native
- * @language zh_CN
- */
- WebAudioSound.MUSIC = "music";
- /**
- * EFFECT
- * @version Egret 2.4
- * @platform Web,Native
- * @language en_US
- */
- /**
- * 音效
- * @version Egret 2.4
- * @platform Web,Native
- * @language zh_CN
- */
- WebAudioSound.EFFECT = "effect";
- return WebAudioSound;
- }(egret.EventDispatcher));
- web.WebAudioSound = WebAudioSound;
- __reflect(WebAudioSound.prototype, "egret.web.WebAudioSound", ["egret.Sound"]);
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- * @inheritDoc
- */
- var WebAudioSoundChannel = (function (_super) {
- __extends(WebAudioSoundChannel, _super);
- /**
- * @private
- */
- function WebAudioSoundChannel() {
- var _this = _super.call(this) || this;
- /**
- * @private
- */
- _this.$startTime = 0;
- /**
- * @private
- */
- _this.bufferSource = null;
- /**
- * @private
- */
- _this.context = web.WebAudioDecode.ctx;
- //声音是否已经播放完成
- _this.isStopped = false;
- /**
- * @private
- */
- _this._currentTime = 0;
- /**
- * @private
- */
- _this._volume = 1;
- /**
- * @private
- */
- _this.onPlayEnd = function () {
- if (_this.$loops == 1) {
- _this.stop();
- _this.dispatchEventWith(egret.Event.SOUND_COMPLETE);
- return;
- }
- if (_this.$loops > 0) {
- _this.$loops--;
- }
- /////////////
- _this.$play();
- };
- /**
- * @private
- */
- _this._startTime = 0;
- if (_this.context["createGain"]) {
- _this.gain = _this.context["createGain"]();
- }
- else {
- _this.gain = _this.context["createGainNode"]();
- }
- return _this;
- }
- WebAudioSoundChannel.prototype.$play = function () {
- if (this.isStopped) {
- egret.$error(1036);
- return;
- }
- if (this.bufferSource) {
- this.bufferSource.onended = null;
- this.bufferSource = null;
- }
- var context = this.context;
- var gain = this.gain;
- var bufferSource = context.createBufferSource();
- this.bufferSource = bufferSource;
- bufferSource.buffer = this.$audioBuffer;
- bufferSource.connect(gain);
- gain.connect(context.destination);
- bufferSource.onended = this.onPlayEnd;
- this._startTime = Date.now();
- this.gain.gain.value = this._volume;
- bufferSource.start(0, this.$startTime);
- this._currentTime = 0;
- };
- WebAudioSoundChannel.prototype.stop = function () {
- if (this.bufferSource) {
- var sourceNode = this.bufferSource;
- if (sourceNode.stop) {
- sourceNode.stop(0);
- }
- else {
- sourceNode.noteOff(0);
- }
- sourceNode.onended = null;
- sourceNode.disconnect();
- this.bufferSource = null;
- this.$audioBuffer = null;
- }
- if (!this.isStopped) {
- egret.sys.$popSoundChannel(this);
- }
- this.isStopped = true;
- };
- Object.defineProperty(WebAudioSoundChannel.prototype, "volume", {
- /**
- * @private
- * @inheritDoc
- */
- get: function () {
- return this._volume;
- },
- /**
- * @inheritDoc
- */
- set: function (value) {
- if (this.isStopped) {
- egret.$error(1036);
- return;
- }
- this._volume = value;
- this.gain.gain.value = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WebAudioSoundChannel.prototype, "position", {
- /**
- * @private
- * @inheritDoc
- */
- get: function () {
- if (this.bufferSource) {
- return (Date.now() - this._startTime) / 1000 + this.$startTime;
- }
- return 0;
- },
- enumerable: true,
- configurable: true
- });
- return WebAudioSoundChannel;
- }(egret.EventDispatcher));
- web.WebAudioSoundChannel = WebAudioSoundChannel;
- __reflect(WebAudioSoundChannel.prototype, "egret.web.WebAudioSoundChannel", ["egret.SoundChannel", "egret.IEventDispatcher"]);
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- * @inheritDoc
- */
- var WebVideo = (function (_super) {
- __extends(WebVideo, _super);
- /**
- * @inheritDoc
- */
- function WebVideo(url, cache) {
- if (cache === void 0) { cache = true; }
- var _this = _super.call(this) || this;
- /**
- * @private
- */
- _this.loaded = false;
- /**
- * @private
- */
- _this.closed = false;
- /**
- * @private
- */
- _this.heightSet = NaN;
- /**
- * @private
- */
- _this.widthSet = NaN;
- /**
- * @private
- * pc上视频卡住的时候不能暂停
- */
- _this.waiting = false;
- /**
- * @private
- * 用户是否设置了 pause
- */
- _this.userPause = false;
- /**
- * @private
- * 用户是否设置了 play
- */
- _this.userPlay = false;
- _this.isPlayed = false;
- _this.screenChanged = function (e) {
- var isfullscreen = document.fullscreenEnabled || document.webkitIsFullScreen;
- if (!isfullscreen) {
- _this.checkFullScreen(false);
- if (!egret.Capabilities.isMobile) {
- _this._fullscreen = isfullscreen;
- }
- }
- };
- _this._fullscreen = true;
- /**
- * @private
- *
- */
- _this.onVideoLoaded = function () {
- _this.video.removeEventListener("canplay", _this.onVideoLoaded);
- var video = _this.video;
- _this.loaded = true;
- //video.pause();
- if (_this.posterData) {
- _this.posterData.width = _this.getPlayWidth();
- _this.posterData.height = _this.getPlayHeight();
- }
- video.width = video.videoWidth;
- video.height = video.videoHeight;
- window.setTimeout(function () {
- _this.dispatchEventWith(egret.Event.COMPLETE);
- }, 200);
- };
- _this.$renderNode = new egret.sys.BitmapNode();
- _this.src = url;
- _this.once(egret.Event.ADDED_TO_STAGE, _this.loadPoster, _this);
- if (url) {
- _this.load();
- }
- return _this;
- }
- WebVideo.prototype.createNativeDisplayObject = function () {
- this.$nativeDisplayObject = new egret_native.NativeDisplayObject(1 /* BITMAP */);
- };
- /**
- * @inheritDoc
- */
- WebVideo.prototype.load = function (url, cache) {
- var _this = this;
- if (cache === void 0) { cache = true; }
- url = url || this.src;
- this.src = url;
- if (true && !url) {
- egret.$error(3002);
- }
- if (this.video && this.video.src == url) {
- return;
- }
- var video;
- if (!this.video || egret.Capabilities.isMobile) {
- video = document.createElement("video");
- this.video = video;
- video.controls = null;
- }
- else {
- video = this.video;
- }
- video.src = url;
- video.setAttribute("autoplay", "autoplay");
- video.setAttribute("webkit-playsinline", "true");
- video.addEventListener("canplay", this.onVideoLoaded);
- video.addEventListener("error", function () { return _this.onVideoError(); });
- video.addEventListener("ended", function () { return _this.onVideoEnded(); });
- var firstPause = false;
- video.addEventListener("canplay", function () {
- _this.waiting = false;
- if (!firstPause) {
- firstPause = true;
- video.pause();
- }
- else {
- if (_this.userPause) {
- _this.pause();
- }
- else if (_this.userPlay) {
- _this.play();
- }
- }
- });
- video.addEventListener("waiting", function () {
- _this.waiting = true;
- });
- video.load();
- this.videoPlay();
- video.style.position = "absolute";
- video.style.top = "0px";
- video.style.zIndex = "-88888";
- video.style.left = "0px";
- video.height = 1;
- video.width = 1;
- };
- /**
- * @inheritDoc
- */
- WebVideo.prototype.play = function (startTime, loop) {
- var _this = this;
- if (loop === void 0) { loop = false; }
- if (this.loaded == false) {
- this.load(this.src);
- this.once(egret.Event.COMPLETE, function (e) { return _this.play(startTime, loop); }, this);
- return;
- }
- this.isPlayed = true;
- var video = this.video;
- if (startTime != undefined) {
- video.currentTime = +startTime || 0;
- }
- video.loop = !!loop;
- if (egret.Capabilities.isMobile) {
- video.style.zIndex = "-88888"; //移动端,就算设置成最小,只要全屏,都会在最上层,而且在自动退出去后,不担心挡住canvas
- }
- else {
- video.style.zIndex = "9999";
- }
- video.style.position = "absolute";
- video.style.top = "0px";
- video.style.left = "0px";
- video.height = video.videoHeight;
- video.width = video.videoWidth;
- if (egret.Capabilities.os != "Windows PC" && egret.Capabilities.os != "Mac OS") {
- window.setTimeout(function () {
- video.width = 0;
- }, 1000);
- }
- this.checkFullScreen(this._fullscreen);
- };
- WebVideo.prototype.videoPlay = function () {
- this.userPause = false;
- if (this.waiting) {
- this.userPlay = true;
- return;
- }
- this.userPlay = false;
- this.video.play();
- };
- WebVideo.prototype.checkFullScreen = function (playFullScreen) {
- var video = this.video;
- if (playFullScreen) {
- if (video.parentElement == null) {
- video.removeAttribute("webkit-playsinline");
- document.body.appendChild(video);
- }
- egret.stopTick(this.markDirty, this);
- this.goFullscreen();
- }
- else {
- if (video.parentElement != null) {
- video.parentElement.removeChild(video);
- }
- video.setAttribute("webkit-playsinline", "true");
- this.setFullScreenMonitor(false);
- egret.startTick(this.markDirty, this);
- if (egret.Capabilities.isMobile) {
- this.video.currentTime = 0;
- this.onVideoEnded();
- return;
- }
- }
- this.videoPlay();
- };
- WebVideo.prototype.goFullscreen = function () {
- var video = this.video;
- var fullscreenType;
- fullscreenType = egret.web.getPrefixStyleName('requestFullscreen', video);
- if (!video[fullscreenType]) {
- fullscreenType = egret.web.getPrefixStyleName('requestFullScreen', video);
- if (!video[fullscreenType]) {
- return true;
- }
- }
- video.removeAttribute("webkit-playsinline");
- video[fullscreenType]();
- this.setFullScreenMonitor(true);
- return true;
- };
- WebVideo.prototype.setFullScreenMonitor = function (use) {
- var video = this.video;
- if (use) {
- video.addEventListener("mozfullscreenchange", this.screenChanged);
- video.addEventListener("webkitfullscreenchange", this.screenChanged);
- video.addEventListener("mozfullscreenerror", this.screenError);
- video.addEventListener("webkitfullscreenerror", this.screenError);
- }
- else {
- video.removeEventListener("mozfullscreenchange", this.screenChanged);
- video.removeEventListener("webkitfullscreenchange", this.screenChanged);
- video.removeEventListener("mozfullscreenerror", this.screenError);
- video.removeEventListener("webkitfullscreenerror", this.screenError);
- }
- };
- WebVideo.prototype.screenError = function () {
- egret.$error(3014);
- };
- WebVideo.prototype.exitFullscreen = function () {
- //退出全屏
- if (document['exitFullscreen']) {
- document['exitFullscreen']();
- }
- else if (document['msExitFullscreen']) {
- document['msExitFullscreen']();
- }
- else if (document['mozCancelFullScreen']) {
- document['mozCancelFullScreen']();
- }
- else if (document['oCancelFullScreen']) {
- document['oCancelFullScreen']();
- }
- else if (document['webkitExitFullscreen']) {
- document['webkitExitFullscreen']();
- }
- else {
- }
- };
- /**
- * @private
- *
- */
- WebVideo.prototype.onVideoEnded = function () {
- this.pause();
- this.isPlayed = false;
- this.dispatchEventWith(egret.Event.ENDED);
- };
- /**
- * @private
- *
- */
- WebVideo.prototype.onVideoError = function () {
- this.dispatchEventWith(egret.IOErrorEvent.IO_ERROR);
- };
- /**
- * @inheritDoc
- */
- WebVideo.prototype.close = function () {
- var _this = this;
- this.closed = true;
- this.video.removeEventListener("canplay", this.onVideoLoaded);
- this.video.removeEventListener("error", function () { return _this.onVideoError(); });
- this.video.removeEventListener("ended", function () { return _this.onVideoEnded(); });
- this.pause();
- if (this.loaded == false && this.video)
- this.video.src = "";
- if (this.video && this.video.parentElement) {
- this.video.parentElement.removeChild(this.video);
- this.video = null;
- }
- this.loaded = false;
- };
- /**
- * @inheritDoc
- */
- WebVideo.prototype.pause = function () {
- this.userPlay = false;
- if (this.waiting) {
- this.userPause = true;
- return;
- }
- this.userPause = false;
- this.video.pause();
- egret.stopTick(this.markDirty, this);
- };
- Object.defineProperty(WebVideo.prototype, "volume", {
- /**
- * @inheritDoc
- */
- get: function () {
- if (!this.video)
- return 1;
- return this.video.volume;
- },
- /**
- * @inheritDoc
- */
- set: function (value) {
- if (!this.video)
- return;
- this.video.volume = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WebVideo.prototype, "position", {
- /**
- * @inheritDoc
- */
- get: function () {
- if (!this.video)
- return 0;
- return this.video.currentTime;
- },
- /**
- * @inheritDoc
- */
- set: function (value) {
- if (!this.video)
- return;
- this.video.currentTime = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WebVideo.prototype, "fullscreen", {
- /**
- * @inheritDoc
- */
- get: function () {
- return this._fullscreen;
- },
- /**
- * @inheritDoc
- */
- set: function (value) {
- if (egret.Capabilities.isMobile) {
- return;
- }
- this._fullscreen = !!value;
- if (this.video && this.video.paused == false) {
- this.checkFullScreen(this._fullscreen);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WebVideo.prototype, "bitmapData", {
- /**
- * @inheritDoc
- */
- get: function () {
- if (!this.video || !this.loaded)
- return null;
- if (!this._bitmapData) {
- this.video.width = this.video.videoWidth;
- this.video.height = this.video.videoHeight;
- this._bitmapData = new egret.BitmapData(this.video);
- this._bitmapData.$deleteSource = false;
- }
- return this._bitmapData;
- },
- enumerable: true,
- configurable: true
- });
- WebVideo.prototype.loadPoster = function () {
- var _this = this;
- var poster = this.poster;
- if (!poster)
- return;
- var imageLoader = new egret.ImageLoader();
- imageLoader.once(egret.Event.COMPLETE, function (e) {
- var posterData = imageLoader.data;
- _this.posterData = imageLoader.data;
- _this.$renderDirty = true;
- _this.posterData.width = _this.getPlayWidth();
- _this.posterData.height = _this.getPlayHeight();
- if (egret.nativeRender) {
- var texture = new egret.Texture();
- texture._setBitmapData(_this.posterData);
- _this.$nativeDisplayObject.setBitmapData(texture);
- }
- }, this);
- imageLoader.load(poster);
- };
- /**
- * @private
- */
- WebVideo.prototype.$measureContentBounds = function (bounds) {
- var bitmapData = this.bitmapData;
- var posterData = this.posterData;
- if (bitmapData) {
- bounds.setTo(0, 0, this.getPlayWidth(), this.getPlayHeight());
- }
- else if (posterData) {
- bounds.setTo(0, 0, this.getPlayWidth(), this.getPlayHeight());
- }
- else {
- bounds.setEmpty();
- }
- };
- WebVideo.prototype.getPlayWidth = function () {
- if (!isNaN(this.widthSet)) {
- return this.widthSet;
- }
- if (this.bitmapData) {
- return this.bitmapData.width;
- }
- if (this.posterData) {
- return this.posterData.width;
- }
- return NaN;
- };
- WebVideo.prototype.getPlayHeight = function () {
- if (!isNaN(this.heightSet)) {
- return this.heightSet;
- }
- if (this.bitmapData) {
- return this.bitmapData.height;
- }
- if (this.posterData) {
- return this.posterData.height;
- }
- return NaN;
- };
- /**
- * @private
- */
- WebVideo.prototype.$updateRenderNode = function () {
- var node = this.$renderNode;
- var bitmapData = this.bitmapData;
- var posterData = this.posterData;
- var width = this.getPlayWidth();
- var height = this.getPlayHeight();
- if ((!this.isPlayed || egret.Capabilities.isMobile) && posterData) {
- node.image = posterData;
- node.imageWidth = width;
- node.imageHeight = height;
- node.drawImage(0, 0, posterData.width, posterData.height, 0, 0, width, height);
- }
- else if (this.isPlayed && bitmapData) {
- node.image = bitmapData;
- node.imageWidth = bitmapData.width;
- node.imageHeight = bitmapData.height;
- egret.WebGLUtils.deleteWebGLTexture(bitmapData.webGLTexture);
- bitmapData.webGLTexture = null;
- node.drawImage(0, 0, bitmapData.width, bitmapData.height, 0, 0, width, height);
- }
- };
- WebVideo.prototype.markDirty = function () {
- this.$renderDirty = true;
- return true;
- };
- /**
- * @private
- * 设置显示高度
- */
- WebVideo.prototype.$setHeight = function (value) {
- this.heightSet = value;
- if (this.paused) {
- var self_1 = this;
- this.$renderDirty = true;
- window.setTimeout(function () {
- self_1.$renderDirty = false;
- }, 200);
- }
- _super.prototype.$setHeight.call(this, value);
- };
- /**
- * @private
- * 设置显示宽度
- */
- WebVideo.prototype.$setWidth = function (value) {
- this.widthSet = value;
- if (this.paused) {
- var self_2 = this;
- this.$renderDirty = true;
- window.setTimeout(function () {
- self_2.$renderDirty = false;
- }, 200);
- }
- _super.prototype.$setWidth.call(this, value);
- };
- Object.defineProperty(WebVideo.prototype, "paused", {
- get: function () {
- if (this.video) {
- return this.video.paused;
- }
- return true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WebVideo.prototype, "length", {
- /**
- * @inheritDoc
- */
- get: function () {
- if (this.video) {
- return this.video.duration;
- }
- throw new Error("Video not loaded!");
- },
- enumerable: true,
- configurable: true
- });
- return WebVideo;
- }(egret.DisplayObject));
- web.WebVideo = WebVideo;
- __reflect(WebVideo.prototype, "egret.web.WebVideo", ["egret.Video", "egret.DisplayObject"]);
- egret.Video = WebVideo;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var WebHttpRequest = (function (_super) {
- __extends(WebHttpRequest, _super);
- /**
- * @private
- */
- function WebHttpRequest() {
- var _this = _super.call(this) || this;
- /**
- * @private
- */
- _this._url = "";
- _this._method = "";
- return _this;
- }
- Object.defineProperty(WebHttpRequest.prototype, "response", {
- /**
- * @private
- * 本次请求返回的数据,数据类型根据responseType设置的值确定。
- */
- get: function () {
- if (!this._xhr) {
- return null;
- }
- if (this._xhr.response != undefined) {
- return this._xhr.response;
- }
- if (this._responseType == "text") {
- return this._xhr.responseText;
- }
- if (this._responseType == "arraybuffer" && /msie 9.0/i.test(navigator.userAgent)) {
- var w = window;
- return w.convertResponseBodyToText(this._xhr["responseBody"]);
- }
- if (this._responseType == "document") {
- return this._xhr.responseXML;
- }
- /*if (this._xhr.responseXML) {
- return this._xhr.responseXML;
- }
- if (this._xhr.responseText != undefined) {
- return this._xhr.responseText;
- }*/
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WebHttpRequest.prototype, "responseType", {
- /**
- * @private
- * 设置返回的数据格式,请使用 HttpResponseType 里定义的枚举值。设置非法的值或不设置,都将使用HttpResponseType.TEXT。
- */
- get: function () {
- return this._responseType;
- },
- set: function (value) {
- this._responseType = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WebHttpRequest.prototype, "withCredentials", {
- /**
- * @private
- * 表明在进行跨站(cross-site)的访问控制(Access-Control)请求时,是否使用认证信息(例如cookie或授权的header)。 默认为 false。(这个标志不会影响同站的请求)
- */
- get: function () {
- return this._withCredentials;
- },
- set: function (value) {
- this._withCredentials = value;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * @private
- *
- * @returns
- */
- WebHttpRequest.prototype.getXHR = function () {
- if (window["XMLHttpRequest"]) {
- return new window["XMLHttpRequest"]();
- }
- else {
- return new ActiveXObject("MSXML2.XMLHTTP");
- }
- };
- /**
- * @private
- * 初始化一个请求.注意,若在已经发出请求的对象上调用此方法,相当于立即调用abort().
- * @param url 该请求所要访问的URL该请求所要访问的URL
- * @param method 请求所使用的HTTP方法, 请使用 HttpMethod 定义的枚举值.
- */
- WebHttpRequest.prototype.open = function (url, method) {
- if (method === void 0) { method = "GET"; }
- this._url = url;
- this._method = method;
- if (this._xhr) {
- this._xhr.abort();
- this._xhr = null;
- }
- this._xhr = this.getXHR(); //new XMLHttpRequest();
- this._xhr.onreadystatechange = this.onReadyStateChange.bind(this);
- this._xhr.onprogress = this.updateProgress.bind(this);
- this._xhr.open(this._method, this._url, true);
- };
- /**
- * @private
- * 发送请求.
- * @param data 需要发送的数据
- */
- WebHttpRequest.prototype.send = function (data) {
- if (this._responseType != null) {
- this._xhr.responseType = this._responseType;
- }
- if (this._withCredentials != null) {
- this._xhr.withCredentials = this._withCredentials;
- }
- if (this.headerObj) {
- for (var key in this.headerObj) {
- this._xhr.setRequestHeader(key, this.headerObj[key]);
- }
- }
- this._xhr.send(data);
- };
- /**
- * @private
- * 如果请求已经被发送,则立刻中止请求.
- */
- WebHttpRequest.prototype.abort = function () {
- if (this._xhr) {
- this._xhr.abort();
- }
- };
- /**
- * @private
- * 返回所有响应头信息(响应头名和值), 如果响应头还没接受,则返回"".
- */
- WebHttpRequest.prototype.getAllResponseHeaders = function () {
- if (!this._xhr) {
- return null;
- }
- var result = this._xhr.getAllResponseHeaders();
- return result ? result : "";
- };
- /**
- * @private
- * 给指定的HTTP请求头赋值.在这之前,您必须确认已经调用 open() 方法打开了一个url.
- * @param header 将要被赋值的请求头名称.
- * @param value 给指定的请求头赋的值.
- */
- WebHttpRequest.prototype.setRequestHeader = function (header, value) {
- if (!this.headerObj) {
- this.headerObj = {};
- }
- this.headerObj[header] = value;
- };
- /**
- * @private
- * 返回指定的响应头的值, 如果响应头还没被接受,或该响应头不存在,则返回"".
- * @param header 要返回的响应头名称
- */
- WebHttpRequest.prototype.getResponseHeader = function (header) {
- if (!this._xhr) {
- return null;
- }
- var result = this._xhr.getResponseHeader(header);
- return result ? result : "";
- };
- /**
- * @private
- */
- WebHttpRequest.prototype.onReadyStateChange = function () {
- var xhr = this._xhr;
- if (xhr.readyState == 4) {
- var ioError_1 = (xhr.status >= 400 || xhr.status == 0);
- var url_1 = this._url;
- var self_3 = this;
- window.setTimeout(function () {
- if (ioError_1) {
- if (true && !self_3.hasEventListener(egret.IOErrorEvent.IO_ERROR)) {
- egret.$error(1011, url_1);
- }
- self_3.dispatchEventWith(egret.IOErrorEvent.IO_ERROR);
- }
- else {
- self_3.dispatchEventWith(egret.Event.COMPLETE);
- }
- }, 0);
- }
- };
- /**
- * @private
- */
- WebHttpRequest.prototype.updateProgress = function (event) {
- if (event.lengthComputable) {
- egret.ProgressEvent.dispatchProgressEvent(this, egret.ProgressEvent.PROGRESS, event.loaded, event.total);
- }
- };
- return WebHttpRequest;
- }(egret.EventDispatcher));
- web.WebHttpRequest = WebHttpRequest;
- __reflect(WebHttpRequest.prototype, "egret.web.WebHttpRequest", ["egret.HttpRequest"]);
- egret.HttpRequest = WebHttpRequest;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- var winURL = window["URL"] || window["webkitURL"];
- /**
- * @private
- * ImageLoader 类可用于加载图像(JPG、PNG 或 GIF)文件。使用 load() 方法来启动加载。被加载的图像对象数据将存储在 ImageLoader.data 属性上 。
- */
- var WebImageLoader = (function (_super) {
- __extends(WebImageLoader, _super);
- function WebImageLoader() {
- var _this = _super !== null && _super.apply(this, arguments) || this;
- /**
- * @private
- * 使用 load() 方法加载成功的 BitmapData 图像数据。
- */
- _this.data = null;
- /**
- * @private
- * 当从其他站点加载一个图片时,指定是否启用跨域资源共享(CORS),默认值为null。
- * 可以设置为"anonymous","use-credentials"或null,设置为其他值将等同于"anonymous"。
- */
- _this._crossOrigin = null;
- /**
- * @private
- * 标记crossOrigin有没有被设置过,设置过之后使用设置的属性
- */
- _this._hasCrossOriginSet = false;
- /**
- * @private
- */
- _this.currentImage = null;
- /**
- * @private
- */
- _this.request = null;
- return _this;
- }
- Object.defineProperty(WebImageLoader.prototype, "crossOrigin", {
- get: function () {
- return this._crossOrigin;
- },
- set: function (value) {
- this._hasCrossOriginSet = true;
- this._crossOrigin = value;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * @private
- * 启动一次图像加载。注意:若之前已经调用过加载请求,重新调用 load() 将终止先前的请求,并开始新的加载。
- * @param url 要加载的图像文件的地址。
- */
- WebImageLoader.prototype.load = function (url) {
- if (web.Html5Capatibility._canUseBlob
- && url.indexOf("wxLocalResource:") != 0 //微信专用不能使用 blob
- && url.indexOf("data:") != 0
- && url.indexOf("http:") != 0
- && url.indexOf("https:") != 0) {
- var request = this.request;
- if (!request) {
- request = this.request = new egret.web.WebHttpRequest();
- request.addEventListener(egret.Event.COMPLETE, this.onBlobLoaded, this);
- request.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onBlobError, this);
- request.responseType = "blob";
- }
- if (true) {
- this.currentURL = url;
- }
- request.open(url);
- request.send();
- }
- else {
- this.loadImage(url);
- }
- };
- /**
- * @private
- */
- WebImageLoader.prototype.onBlobLoaded = function (event) {
- var blob = this.request.response;
- this.request = undefined;
- this.loadImage(winURL.createObjectURL(blob));
- };
- /**
- * @private
- */
- WebImageLoader.prototype.onBlobError = function (event) {
- this.dispatchIOError(this.currentURL);
- this.request = undefined;
- };
- /**
- * @private
- */
- WebImageLoader.prototype.loadImage = function (src) {
- var image = new Image();
- this.data = null;
- this.currentImage = image;
- if (this._hasCrossOriginSet) {
- if (this._crossOrigin) {
- image.crossOrigin = this._crossOrigin;
- }
- }
- else {
- if (WebImageLoader.crossOrigin) {
- image.crossOrigin = WebImageLoader.crossOrigin;
- }
- }
- /*else {
- if (image.hasAttribute("crossOrigin")) {//兼容猎豹
- image.removeAttribute("crossOrigin");
- }
- }*/
- image.onload = this.onImageComplete.bind(this);
- image.onerror = this.onLoadError.bind(this);
- image.src = src;
- };
- /**
- * @private
- */
- WebImageLoader.prototype.onImageComplete = function (event) {
- var image = this.getImage(event);
- if (!image) {
- return;
- }
- this.data = new egret.BitmapData(image);
- var self = this;
- window.setTimeout(function () {
- self.dispatchEventWith(egret.Event.COMPLETE);
- }, 0);
- };
- /**
- * @private
- */
- WebImageLoader.prototype.onLoadError = function (event) {
- var image = this.getImage(event);
- if (!image) {
- return;
- }
- this.dispatchIOError(image.src);
- };
- WebImageLoader.prototype.dispatchIOError = function (url) {
- var self = this;
- window.setTimeout(function () {
- if (true && !self.hasEventListener(egret.IOErrorEvent.IO_ERROR)) {
- egret.$error(1011, url);
- }
- self.dispatchEventWith(egret.IOErrorEvent.IO_ERROR);
- }, 0);
- };
- /**
- * @private
- */
- WebImageLoader.prototype.getImage = function (event) {
- var image = event.target;
- var url = image.src;
- if (url.indexOf("blob:") == 0) {
- try {
- winURL.revokeObjectURL(image.src);
- }
- catch (e) {
- egret.$warn(1037);
- }
- }
- image.onerror = null;
- image.onload = null;
- if (this.currentImage !== image) {
- return null;
- }
- this.currentImage = null;
- return image;
- };
- /**
- * @private
- * 指定是否启用跨域资源共享,如果ImageLoader实例有设置过crossOrigin属性将使用设置的属性
- */
- WebImageLoader.crossOrigin = null;
- return WebImageLoader;
- }(egret.EventDispatcher));
- web.WebImageLoader = WebImageLoader;
- __reflect(WebImageLoader.prototype, "egret.web.WebImageLoader", ["egret.ImageLoader"]);
- egret.ImageLoader = WebImageLoader;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @classdesc
- * @extends egret.StageText
- * @private
- */
- var HTML5StageText = (function (_super) {
- __extends(HTML5StageText, _super);
- /**
- * @private
- */
- function HTML5StageText() {
- var _this = _super.call(this) || this;
- /**
- * @private
- */
- _this._isNeedShow = false;
- /**
- * @private
- */
- _this.inputElement = null;
- /**
- * @private
- */
- _this.inputDiv = null;
- /**
- * @private
- */
- _this._gscaleX = 0;
- /**
- * @private
- */
- _this._gscaleY = 0;
- /**
- * @private
- */
- _this.textValue = "";
- /**
- * @private
- */
- _this.colorValue = 0xffffff;
- /**
- * @private
- */
- _this._styleInfoes = {};
- return _this;
- }
- /**
- * @private
- *
- * @param textfield
- */
- HTML5StageText.prototype.$setTextField = function (textfield) {
- this.$textfield = textfield;
- return true;
- };
- /**
- * @private
- *
- */
- HTML5StageText.prototype.$addToStage = function () {
- this.htmlInput = egret.web.$getTextAdapter(this.$textfield);
- };
- /**
- * @private
- *
- */
- HTML5StageText.prototype._initElement = function () {
- var point = this.$textfield.localToGlobal(0, 0);
- var x = point.x;
- var y = point.y;
- // let m = this.$textfield.$renderNode.renderMatrix;
- // let cX = m.a;
- // let cY = m.d;
- var scaleX = this.htmlInput.$scaleX;
- var scaleY = this.htmlInput.$scaleY;
- this.inputDiv.style.left = x * scaleX + "px";
- this.inputDiv.style.top = y * scaleY + "px";
- if (this.$textfield.multiline && this.$textfield.height > this.$textfield.size) {
- this.inputDiv.style.top = (y) * scaleY + "px";
- this.inputElement.style.top = (-this.$textfield.lineSpacing / 2) * scaleY + "px";
- }
- else {
- this.inputDiv.style.top = y * scaleY + "px";
- this.inputElement.style.top = 0 + "px";
- }
- var node = this.$textfield;
- var cX = 1;
- var cY = 1;
- var rotation = 0;
- while (node.parent) {
- cX *= node.scaleX;
- cY *= node.scaleY;
- rotation += node.rotation;
- node = node.parent;
- }
- var transformKey = egret.web.getPrefixStyleName("transform");
- this.inputDiv.style[transformKey] = "rotate(" + rotation + "deg)";
- this._gscaleX = scaleX * cX;
- this._gscaleY = scaleY * cY;
- };
- /**
- * @private
- *
- */
- HTML5StageText.prototype.$show = function () {
- if (!this.htmlInput.isCurrentStageText(this)) {
- this.inputElement = this.htmlInput.getInputElement(this);
- if (!this.$textfield.multiline) {
- this.inputElement.type = this.$textfield.inputType;
- }
- else {
- this.inputElement.type = "text";
- }
- this.inputDiv = this.htmlInput._inputDIV;
- }
- else {
- this.inputElement.onblur = null;
- }
- this.htmlInput._needShow = true;
- //标记当前文本被选中
- this._isNeedShow = true;
- this._initElement();
- };
- /**
- * @private
- *
- */
- HTML5StageText.prototype.onBlurHandler = function () {
- this.htmlInput.clearInputElement();
- window.scrollTo(0, 0);
- };
- /**
- * @private
- *
- */
- HTML5StageText.prototype.executeShow = function () {
- var self = this;
- //打开
- this.inputElement.value = this.$getText();
- if (this.inputElement.onblur == null) {
- this.inputElement.onblur = this.onBlurHandler.bind(this);
- }
- this.$resetStageText();
- if (this.$textfield.maxChars > 0) {
- this.inputElement.setAttribute("maxlength", this.$textfield.maxChars);
- }
- else {
- this.inputElement.removeAttribute("maxlength");
- }
- this.inputElement.selectionStart = this.inputElement.value.length;
- this.inputElement.selectionEnd = this.inputElement.value.length;
- this.inputElement.focus();
- };
- /**
- * @private
- */
- HTML5StageText.prototype.$hide = function () {
- if (this.htmlInput) {
- this.htmlInput.disconnectStageText(this);
- }
- };
- /**
- * @private
- *
- * @returns
- */
- HTML5StageText.prototype.$getText = function () {
- if (!this.textValue) {
- this.textValue = "";
- }
- return this.textValue;
- };
- /**
- * @private
- *
- * @param value
- */
- HTML5StageText.prototype.$setText = function (value) {
- this.textValue = value;
- this.resetText();
- return true;
- };
- /**
- * @private
- *
- */
- HTML5StageText.prototype.resetText = function () {
- if (this.inputElement) {
- this.inputElement.value = this.textValue;
- }
- };
- HTML5StageText.prototype.$setColor = function (value) {
- this.colorValue = value;
- this.resetColor();
- return true;
- };
- /**
- * @private
- *
- */
- HTML5StageText.prototype.resetColor = function () {
- if (this.inputElement) {
- this.setElementStyle("color", egret.toColorString(this.colorValue));
- }
- };
- HTML5StageText.prototype.$onBlur = function () {
- };
- /**
- * @private
- *
- */
- HTML5StageText.prototype._onInput = function () {
- var self = this;
- window.setTimeout(function () {
- if (self.inputElement && self.inputElement.selectionStart == self.inputElement.selectionEnd) {
- self.textValue = self.inputElement.value;
- egret.Event.dispatchEvent(self, "updateText", false);
- }
- }, 0);
- };
- HTML5StageText.prototype.setAreaHeight = function () {
- var textfield = this.$textfield;
- if (textfield.multiline) {
- var textheight = egret.TextFieldUtils.$getTextHeight(textfield);
- if (textfield.height <= textfield.size) {
- this.setElementStyle("height", (textfield.size) * this._gscaleY + "px");
- this.setElementStyle("padding", "0px");
- this.setElementStyle("lineHeight", (textfield.size) * this._gscaleY + "px");
- }
- else if (textfield.height < textheight) {
- this.setElementStyle("height", (textfield.height) * this._gscaleY + "px");
- this.setElementStyle("padding", "0px");
- this.setElementStyle("lineHeight", (textfield.size + textfield.lineSpacing) * this._gscaleY + "px");
- }
- else {
- this.setElementStyle("height", (textheight + textfield.lineSpacing) * this._gscaleY + "px");
- var rap = (textfield.height - textheight) * this._gscaleY;
- var valign = egret.TextFieldUtils.$getValign(textfield);
- var top_1 = rap * valign;
- var bottom = rap - top_1;
- this.setElementStyle("padding", top_1 + "px 0px " + bottom + "px 0px");
- this.setElementStyle("lineHeight", (textfield.size + textfield.lineSpacing) * this._gscaleY + "px");
- }
- }
- };
- /**
- * @private
- *
- * @param e
- */
- HTML5StageText.prototype._onClickHandler = function (e) {
- if (this._isNeedShow) {
- e.stopImmediatePropagation();
- //e.preventDefault();
- this._isNeedShow = false;
- this.executeShow();
- this.dispatchEvent(new egret.Event("focus"));
- }
- };
- /**
- * @private
- *
- */
- HTML5StageText.prototype._onDisconnect = function () {
- this.inputElement = null;
- this.dispatchEvent(new egret.Event("blur"));
- };
- /**
- * @private
- *
- * @param style
- * @param value
- */
- HTML5StageText.prototype.setElementStyle = function (style, value) {
- if (this.inputElement) {
- if (this._styleInfoes[style] != value) {
- this.inputElement.style[style] = value;
- //this._styleInfoes[style] = value;
- }
- }
- };
- /**
- * @private
- *
- */
- HTML5StageText.prototype.$removeFromStage = function () {
- if (this.inputElement) {
- this.htmlInput.disconnectStageText(this);
- }
- };
- /**
- * 修改位置
- * @private
- */
- HTML5StageText.prototype.$resetStageText = function () {
- if (this.inputElement) {
- var textfield = this.$textfield;
- this.setElementStyle("fontFamily", textfield.fontFamily);
- this.setElementStyle("fontStyle", textfield.italic ? "italic" : "normal");
- this.setElementStyle("fontWeight", textfield.bold ? "bold" : "normal");
- this.setElementStyle("textAlign", textfield.textAlign);
- this.setElementStyle("fontSize", textfield.size * this._gscaleY + "px");
- this.setElementStyle("color", egret.toColorString(textfield.textColor));
- var tw = void 0;
- if (textfield.stage) {
- tw = textfield.localToGlobal(0, 0).x;
- tw = Math.min(textfield.width, textfield.stage.stageWidth - tw);
- }
- else {
- tw = textfield.width;
- }
- this.setElementStyle("width", tw * this._gscaleX + "px");
- this.setElementStyle("verticalAlign", textfield.verticalAlign);
- if (textfield.multiline) {
- this.setAreaHeight();
- }
- else {
- this.setElementStyle("lineHeight", (textfield.size) * this._gscaleY + "px");
- if (textfield.height < textfield.size) {
- this.setElementStyle("height", (textfield.size) * this._gscaleY + "px");
- var bottom = (textfield.size / 2) * this._gscaleY;
- this.setElementStyle("padding", "0px 0px " + bottom + "px 0px");
- }
- else {
- this.setElementStyle("height", (textfield.size) * this._gscaleY + "px");
- var rap = (textfield.height - textfield.size) * this._gscaleY;
- var valign = egret.TextFieldUtils.$getValign(textfield);
- var top_2 = rap * valign;
- var bottom = rap - top_2;
- if (bottom < textfield.size / 2 * this._gscaleY) {
- bottom = textfield.size / 2 * this._gscaleY;
- }
- this.setElementStyle("padding", top_2 + "px 0px " + bottom + "px 0px");
- }
- }
- this.inputDiv.style.clip = "rect(0px " + (textfield.width * this._gscaleX) + "px " + (textfield.height * this._gscaleY) + "px 0px)";
- this.inputDiv.style.height = textfield.height * this._gscaleY + "px";
- this.inputDiv.style.width = tw * this._gscaleX + "px";
- }
- };
- return HTML5StageText;
- }(egret.EventDispatcher));
- web.HTML5StageText = HTML5StageText;
- __reflect(HTML5StageText.prototype, "egret.web.HTML5StageText", ["egret.StageText"]);
- egret.StageText = HTML5StageText;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var HTMLInput = (function () {
- function HTMLInput() {
- /**
- * @private
- */
- this._needShow = false;
- /**
- * @private
- */
- this.$scaleX = 1;
- /**
- * @private
- */
- this.$scaleY = 1;
- }
- /**
- * @private
- *
- * @returns
- */
- HTMLInput.prototype.isInputOn = function () {
- return this._stageText != null;
- };
- /**
- * @private
- *
- * @param stageText
- * @returns
- */
- HTMLInput.prototype.isCurrentStageText = function (stageText) {
- return this._stageText == stageText;
- };
- /**
- * @private
- *
- * @param dom
- */
- HTMLInput.prototype.initValue = function (dom) {
- dom.style.position = "absolute";
- dom.style.left = "0px";
- dom.style.top = "0px";
- dom.style.border = "none";
- dom.style.padding = "0";
- };
- /**
- * @private
- *
- */
- HTMLInput.prototype.$updateSize = function () {
- if (!this.canvas) {
- return;
- }
- this.$scaleX = egret.sys.DisplayList.$canvasScaleX;
- this.$scaleY = egret.sys.DisplayList.$canvasScaleY;
- this.StageDelegateDiv.style.left = this.canvas.style.left;
- this.StageDelegateDiv.style.top = this.canvas.style.top;
- var transformKey = egret.web.getPrefixStyleName("transform");
- this.StageDelegateDiv.style[transformKey] = this.canvas.style[transformKey];
- this.StageDelegateDiv.style[egret.web.getPrefixStyleName("transformOrigin")] = "0% 0% 0px";
- };
- /**
- * @private
- *
- * @param container
- * @param canvas
- * @returns
- */
- HTMLInput.prototype._initStageDelegateDiv = function (container, canvas) {
- this.canvas = canvas;
- var self = this;
- var stageDelegateDiv;
- if (!stageDelegateDiv) {
- stageDelegateDiv = document.createElement("div");
- this.StageDelegateDiv = stageDelegateDiv;
- stageDelegateDiv.id = "StageDelegateDiv";
- container.appendChild(stageDelegateDiv);
- self.initValue(stageDelegateDiv);
- self._inputDIV = document.createElement("div");
- self.initValue(self._inputDIV);
- self._inputDIV.style.width = "0px";
- self._inputDIV.style.height = "0px";
- self._inputDIV.style.left = 0 + "px";
- self._inputDIV.style.top = "-100px";
- self._inputDIV.style[egret.web.getPrefixStyleName("transformOrigin")] = "0% 0% 0px";
- stageDelegateDiv.appendChild(self._inputDIV);
- this.canvas.addEventListener("click", function (e) {
- if (self._needShow) {
- self._needShow = false;
- self._stageText._onClickHandler(e);
- self.show();
- }
- else {
- if (self._inputElement) {
- self.clearInputElement();
- self._inputElement.blur();
- self._inputElement = null;
- }
- }
- });
- self.initInputElement(true);
- self.initInputElement(false);
- }
- };
- //初始化输入框
- HTMLInput.prototype.initInputElement = function (multiline) {
- var self = this;
- //增加1个空的textarea
- var inputElement;
- if (multiline) {
- inputElement = document.createElement("textarea");
- inputElement.style["resize"] = "none";
- self._multiElement = inputElement;
- inputElement.id = "egretTextarea";
- }
- else {
- inputElement = document.createElement("input");
- self._simpleElement = inputElement;
- inputElement.id = "egretInput";
- }
- inputElement.type = "text";
- self._inputDIV.appendChild(inputElement);
- inputElement.setAttribute("tabindex", "-1");
- inputElement.style.width = "1px";
- inputElement.style.height = "12px";
- self.initValue(inputElement);
- inputElement.style.outline = "thin";
- inputElement.style.background = "none";
- inputElement.style.overflow = "hidden";
- inputElement.style.wordBreak = "break-all";
- //隐藏输入框
- inputElement.style.opacity = 0;
- inputElement.oninput = function () {
- if (self._stageText) {
- self._stageText._onInput();
- }
- };
- };
- /**
- * @private
- *
- */
- HTMLInput.prototype.show = function () {
- var self = this;
- var inputElement = self._inputElement;
- //隐藏输入框
- egret.$callAsync(function () {
- inputElement.style.opacity = 1;
- }, self);
- };
- /**
- * @private
- *
- * @param stageText
- */
- HTMLInput.prototype.disconnectStageText = function (stageText) {
- if (this._stageText == null || this._stageText == stageText) {
- this.clearInputElement();
- if (this._inputElement) {
- this._inputElement.blur();
- }
- }
- this._needShow = false;
- };
- /**
- * @private
- *
- */
- HTMLInput.prototype.clearInputElement = function () {
- var self = this;
- if (self._inputElement) {
- self._inputElement.value = "";
- self._inputElement.onblur = null;
- self._inputElement.style.width = "1px";
- self._inputElement.style.height = "12px";
- self._inputElement.style.left = "0px";
- self._inputElement.style.top = "0px";
- self._inputElement.style.opacity = 0;
- var otherElement = void 0;
- if (self._simpleElement == self._inputElement) {
- otherElement = self._multiElement;
- }
- else {
- otherElement = self._simpleElement;
- }
- otherElement.style.display = "block";
- self._inputDIV.style.left = 0 + "px";
- self._inputDIV.style.top = "-100px";
- self._inputDIV.style.height = 0 + "px";
- self._inputDIV.style.width = 0 + "px";
- }
- if (self._stageText) {
- self._stageText._onDisconnect();
- self._stageText = null;
- this.canvas['userTyping'] = false;
- }
- };
- /**
- * @private
- *
- * @param stageText
- * @returns
- */
- HTMLInput.prototype.getInputElement = function (stageText) {
- var self = this;
- self.clearInputElement();
- self._stageText = stageText;
- this.canvas['userTyping'] = true;
- if (self._stageText.$textfield.multiline) {
- self._inputElement = self._multiElement;
- }
- else {
- self._inputElement = self._simpleElement;
- }
- var otherElement;
- if (self._simpleElement == self._inputElement) {
- otherElement = self._multiElement;
- }
- else {
- otherElement = self._simpleElement;
- }
- otherElement.style.display = "none";
- return self._inputElement;
- };
- return HTMLInput;
- }());
- web.HTMLInput = HTMLInput;
- __reflect(HTMLInput.prototype, "egret.web.HTMLInput");
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- (function (egret) {
- var web;
- (function (web) {
- var stageToTextLayerMap = {};
- var stageToCanvasMap = {};
- var stageToContainerMap = {};
- /**
- * @private
- * 获取
- */
- function $getTextAdapter(textfield) {
- var stageHash = textfield.stage ? textfield.stage.$hashCode : 0;
- var adapter = stageToTextLayerMap[stageHash];
- var canvas = stageToCanvasMap[stageHash];
- var container = stageToContainerMap[stageHash];
- if (canvas && container) {
- //adapter._initStageDelegateDiv(container, canvas);
- //adapter.$updateSize();
- delete stageToCanvasMap[stageHash];
- delete stageToContainerMap[stageHash];
- }
- return adapter;
- }
- web.$getTextAdapter = $getTextAdapter;
- /**
- * @private
- */
- function $cacheTextAdapter(adapter, stage, container, canvas) {
- adapter._initStageDelegateDiv(container, canvas);
- stageToTextLayerMap[stage.$hashCode] = adapter;
- stageToCanvasMap[stage.$hashCode] = canvas;
- stageToContainerMap[stage.$hashCode] = container;
- }
- web.$cacheTextAdapter = $cacheTextAdapter;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var context = null;
- /**
- * @private
- */
- var fontCache = {};
- /**
- * 测量文本在指定样式下的宽度。
- * @param text 要测量的文本内容。
- * @param fontFamily 字体名称
- * @param fontSize 字体大小
- * @param bold 是否粗体
- * @param italic 是否斜体
- */
- function measureText(text, fontFamily, fontSize, bold, italic) {
- if (!context) {
- createContext();
- }
- var font = "";
- if (italic)
- font += "italic ";
- if (bold)
- font += "bold ";
- font += (fontSize || 12) + "px ";
- font += (fontFamily || "Arial");
- context.font = font;
- return context.measureText(text).width;
- }
- /**
- * @private
- */
- function createContext() {
- context = egret.sys.canvasHitTestBuffer.context;
- context.textAlign = "left";
- context.textBaseline = "middle";
- }
- egret.sys.measureText = measureText;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * 创建一个canvas。
- */
- function createCanvas(width, height) {
- var canvas = document.createElement("canvas");
- if (!isNaN(width) && !isNaN(height)) {
- canvas.width = width;
- canvas.height = height;
- }
- var context = canvas.getContext("2d");
- if (context["imageSmoothingEnabled"] === undefined) {
- var keys = ["webkitImageSmoothingEnabled", "mozImageSmoothingEnabled", "msImageSmoothingEnabled"];
- var key_1;
- for (var i = keys.length - 1; i >= 0; i--) {
- key_1 = keys[i];
- if (context[key_1] !== void 0) {
- break;
- }
- }
- try {
- Object.defineProperty(context, "imageSmoothingEnabled", {
- get: function () {
- return this[key_1];
- },
- set: function (value) {
- this[key_1] = value;
- }
- });
- }
- catch (e) {
- context["imageSmoothingEnabled"] = context[key_1];
- }
- }
- return canvas;
- }
- var sharedCanvas;
- /**
- * @private
- * Canvas2D渲染缓冲
- */
- var CanvasRenderBuffer = (function () {
- function CanvasRenderBuffer(width, height, root) {
- this.surface = createCanvas(width, height);
- this.context = this.surface.getContext("2d");
- if (this.context) {
- this.context.$offsetX = 0;
- this.context.$offsetY = 0;
- }
- }
- Object.defineProperty(CanvasRenderBuffer.prototype, "width", {
- /**
- * 渲染缓冲的宽度,以像素为单位。
- * @readOnly
- */
- get: function () {
- return this.surface.width;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(CanvasRenderBuffer.prototype, "height", {
- /**
- * 渲染缓冲的高度,以像素为单位。
- * @readOnly
- */
- get: function () {
- return this.surface.height;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * 改变渲染缓冲的大小并清空缓冲区
- * @param width 改变后的宽
- * @param height 改变后的高
- * @param useMaxSize 若传入true,则将改变后的尺寸与已有尺寸对比,保留较大的尺寸。
- */
- CanvasRenderBuffer.prototype.resize = function (width, height, useMaxSize) {
- var surface = this.surface;
- if (useMaxSize) {
- var change = false;
- if (surface.width < width) {
- surface.width = width;
- change = true;
- }
- if (surface.height < height) {
- surface.height = height;
- change = true;
- }
- //尺寸没有变化时,将绘制属性重置
- if (!change) {
- this.context.globalCompositeOperation = "source-over";
- this.context.setTransform(1, 0, 0, 1, 0, 0);
- this.context.globalAlpha = 1;
- }
- }
- else {
- if (surface.width != width) {
- surface.width = width;
- }
- if (surface.height != height) {
- surface.height = height;
- }
- }
- this.clear();
- };
- /**
- * 获取指定区域的像素
- */
- CanvasRenderBuffer.prototype.getPixels = function (x, y, width, height) {
- if (width === void 0) { width = 1; }
- if (height === void 0) { height = 1; }
- return this.context.getImageData(x, y, width, height).data;
- };
- /**
- * 转换成base64字符串,如果图片(或者包含的图片)跨域,则返回null
- * @param type 转换的类型,如: "image/png","image/jpeg"
- */
- CanvasRenderBuffer.prototype.toDataURL = function (type, encoderOptions) {
- return this.surface.toDataURL(type, encoderOptions);
- };
- /**
- * 清空缓冲区数据
- */
- CanvasRenderBuffer.prototype.clear = function () {
- this.context.setTransform(1, 0, 0, 1, 0, 0);
- this.context.clearRect(0, 0, this.surface.width, this.surface.height);
- };
- /**
- * 销毁绘制对象
- */
- CanvasRenderBuffer.prototype.destroy = function () {
- this.surface.width = this.surface.height = 0;
- };
- return CanvasRenderBuffer;
- }());
- web.CanvasRenderBuffer = CanvasRenderBuffer;
- __reflect(CanvasRenderBuffer.prototype, "egret.web.CanvasRenderBuffer", ["egret.sys.RenderBuffer"]);
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided this the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var WebTouchHandler = (function (_super) {
- __extends(WebTouchHandler, _super);
- /**
- * @private
- */
- function WebTouchHandler(stage, canvas) {
- var _this = _super.call(this) || this;
- /**
- * @private
- */
- _this.onTouchBegin = function (event) {
- var location = _this.getLocation(event);
- _this.touch.onTouchBegin(location.x, location.y, event.identifier);
- };
- _this.onMouseMove = function (event) {
- if (event.buttons == 0) {
- _this.onTouchEnd(event);
- }
- else {
- _this.onTouchMove(event);
- }
- };
- /**
- * @private
- */
- _this.onTouchMove = function (event) {
- var location = _this.getLocation(event);
- _this.touch.onTouchMove(location.x, location.y, event.identifier);
- };
- /**
- * @private
- */
- _this.onTouchEnd = function (event) {
- var location = _this.getLocation(event);
- _this.touch.onTouchEnd(location.x, location.y, event.identifier);
- };
- /**
- * @private
- */
- _this.scaleX = 1;
- /**
- * @private
- */
- _this.scaleY = 1;
- /**
- * @private
- */
- _this.rotation = 0;
- _this.canvas = canvas;
- _this.touch = new egret.sys.TouchHandler(stage);
- _this.addListeners();
- return _this;
- }
- /**
- * @private
- * 添加事件监听
- */
- WebTouchHandler.prototype.addListeners = function () {
- var _this = this;
- if (window.navigator.msPointerEnabled) {
- this.canvas.addEventListener("MSPointerDown", function (event) {
- event.identifier = event.pointerId;
- _this.onTouchBegin(event);
- _this.prevent(event);
- }, false);
- this.canvas.addEventListener("MSPointerMove", function (event) {
- event.identifier = event.pointerId;
- _this.onTouchMove(event);
- _this.prevent(event);
- }, false);
- this.canvas.addEventListener("MSPointerUp", function (event) {
- event.identifier = event.pointerId;
- _this.onTouchEnd(event);
- _this.prevent(event);
- }, false);
- }
- else {
- if (!egret.Capabilities.isMobile) {
- this.addMouseListener();
- }
- this.addTouchListener();
- }
- };
- /**
- * @private
- *
- */
- WebTouchHandler.prototype.addMouseListener = function () {
- this.canvas.addEventListener("mousedown", this.onTouchBegin);
- this.canvas.addEventListener("mousemove", this.onMouseMove);
- this.canvas.addEventListener("mouseup", this.onTouchEnd);
- };
- /**
- * @private
- *
- */
- WebTouchHandler.prototype.addTouchListener = function () {
- var _this = this;
- this.canvas.addEventListener("touchstart", function (event) {
- var l = event.changedTouches.length;
- for (var i = 0; i < l; i++) {
- _this.onTouchBegin(event.changedTouches[i]);
- }
- _this.prevent(event);
- }, false);
- this.canvas.addEventListener("touchmove", function (event) {
- var l = event.changedTouches.length;
- for (var i = 0; i < l; i++) {
- _this.onTouchMove(event.changedTouches[i]);
- }
- _this.prevent(event);
- }, false);
- this.canvas.addEventListener("touchend", function (event) {
- var l = event.changedTouches.length;
- for (var i = 0; i < l; i++) {
- _this.onTouchEnd(event.changedTouches[i]);
- }
- _this.prevent(event);
- }, false);
- this.canvas.addEventListener("touchcancel", function (event) {
- var l = event.changedTouches.length;
- for (var i = 0; i < l; i++) {
- _this.onTouchEnd(event.changedTouches[i]);
- }
- _this.prevent(event);
- }, false);
- };
- /**
- * @private
- */
- WebTouchHandler.prototype.prevent = function (event) {
- event.stopPropagation();
- if (event["isScroll"] != true && !this.canvas['userTyping']) {
- event.preventDefault();
- }
- };
- /**
- * @private
- */
- WebTouchHandler.prototype.getLocation = function (event) {
- event.identifier = +event.identifier || 0;
- var doc = document.documentElement;
- var box = this.canvas.getBoundingClientRect();
- var left = box.left + window.pageXOffset - doc.clientLeft;
- var top = box.top + window.pageYOffset - doc.clientTop;
- var x = event.pageX - left, newx = x;
- var y = event.pageY - top, newy = y;
- if (this.rotation == 90) {
- newx = y;
- newy = box.width - x;
- }
- else if (this.rotation == -90) {
- newx = box.height - y;
- newy = x;
- }
- newx = newx / this.scaleX;
- newy = newy / this.scaleY;
- return egret.$TempPoint.setTo(Math.round(newx), Math.round(newy));
- };
- /**
- * @private
- * 更新屏幕当前的缩放比例,用于计算准确的点击位置。
- * @param scaleX 水平方向的缩放比例。
- * @param scaleY 垂直方向的缩放比例。
- */
- WebTouchHandler.prototype.updateScaleMode = function (scaleX, scaleY, rotation) {
- this.scaleX = scaleX;
- this.scaleY = scaleY;
- this.rotation = rotation;
- };
- /**
- * @private
- * 更新同时触摸点的数量
- */
- WebTouchHandler.prototype.$updateMaxTouches = function () {
- this.touch.$initMaxTouches();
- };
- return WebTouchHandler;
- }(egret.HashObject));
- web.WebTouchHandler = WebTouchHandler;
- __reflect(WebTouchHandler.prototype, "egret.web.WebTouchHandler");
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- web.WebLifeCycleHandler = function (context) {
- var handleVisibilityChange = function () {
- if (!document[hidden]) {
- context.resume();
- }
- else {
- context.pause();
- }
- };
- window.addEventListener("focus", context.resume, false);
- window.addEventListener("blur", context.pause, false);
- var hidden, visibilityChange;
- if (typeof document.hidden !== "undefined") {
- hidden = "hidden";
- visibilityChange = "visibilitychange";
- }
- else if (typeof document["mozHidden"] !== "undefined") {
- hidden = "mozHidden";
- visibilityChange = "mozvisibilitychange";
- }
- else if (typeof document["msHidden"] !== "undefined") {
- hidden = "msHidden";
- visibilityChange = "msvisibilitychange";
- }
- else if (typeof document["webkitHidden"] !== "undefined") {
- hidden = "webkitHidden";
- visibilityChange = "webkitvisibilitychange";
- }
- else if (typeof document["oHidden"] !== "undefined") {
- hidden = "oHidden";
- visibilityChange = "ovisibilitychange";
- }
- if ("onpageshow" in window && "onpagehide" in window) {
- window.addEventListener("pageshow", context.resume, false);
- window.addEventListener("pagehide", context.pause, false);
- }
- if (hidden && visibilityChange) {
- document.addEventListener(visibilityChange, handleVisibilityChange, false);
- }
- var ua = navigator.userAgent;
- var isWX = /micromessenger/gi.test(ua);
- var isQQBrowser = /mqq/ig.test(ua);
- var isQQ = /mobile.*qq/gi.test(ua);
- if (isQQ || isWX) {
- isQQBrowser = false;
- }
- if (isQQBrowser) {
- var browser = window["browser"] || {};
- browser.execWebFn = browser.execWebFn || {};
- browser.execWebFn.postX5GamePlayerMessage = function (event) {
- var eventType = event.type;
- if (eventType == "app_enter_background") {
- context.pause();
- }
- else if (eventType == "app_enter_foreground") {
- context.resume();
- }
- };
- window["browser"] = browser;
- }
- };
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var AudioType = (function () {
- function AudioType() {
- }
- /**
- * @private
- */
- AudioType.WEB_AUDIO = 2;
- /**
- * @private
- */
- AudioType.HTML5_AUDIO = 3;
- return AudioType;
- }());
- web.AudioType = AudioType;
- __reflect(AudioType.prototype, "egret.web.AudioType");
- /**
- * html5兼容性配置
- * @private
- */
- var Html5Capatibility = (function (_super) {
- __extends(Html5Capatibility, _super);
- /**
- * @private
- */
- function Html5Capatibility() {
- return _super.call(this) || this;
- }
- /**
- * @private
- *
- */
- Html5Capatibility.$init = function () {
- var ua = navigator.userAgent.toLowerCase();
- Html5Capatibility.ua = ua;
- Html5Capatibility._canUseBlob = false;
- var canUseWebAudio = window["AudioContext"] || window["webkitAudioContext"] || window["mozAudioContext"];
- if (canUseWebAudio) {
- try {
- //防止某些chrome版本创建异常问题
- web.WebAudioDecode.ctx = new (window["AudioContext"] || window["webkitAudioContext"] || window["mozAudioContext"])();
- }
- catch (e) {
- canUseWebAudio = false;
- }
- }
- var audioType = Html5Capatibility._audioType;
- var checkAudioType;
- if ((audioType == AudioType.WEB_AUDIO && canUseWebAudio) || audioType == AudioType.HTML5_AUDIO) {
- checkAudioType = false;
- Html5Capatibility.setAudioType(audioType);
- }
- else {
- checkAudioType = true;
- Html5Capatibility.setAudioType(AudioType.HTML5_AUDIO);
- }
- if (ua.indexOf("android") >= 0) {
- if (checkAudioType && canUseWebAudio) {
- Html5Capatibility.setAudioType(AudioType.WEB_AUDIO);
- }
- }
- else if (ua.indexOf("iphone") >= 0 || ua.indexOf("ipad") >= 0 || ua.indexOf("ipod") >= 0) {
- if (Html5Capatibility.getIOSVersion() >= 7) {
- Html5Capatibility._canUseBlob = true;
- if (checkAudioType && canUseWebAudio) {
- Html5Capatibility.setAudioType(AudioType.WEB_AUDIO);
- }
- }
- }
- var winURL = window["URL"] || window["webkitURL"];
- if (!winURL) {
- Html5Capatibility._canUseBlob = false;
- }
- if (ua.indexOf("egretnative") >= 0) {
- Html5Capatibility.setAudioType(AudioType.HTML5_AUDIO);
- Html5Capatibility._canUseBlob = true;
- }
- egret.Sound = Html5Capatibility._AudioClass;
- };
- Html5Capatibility.setAudioType = function (type) {
- Html5Capatibility._audioType = type;
- switch (type) {
- case AudioType.WEB_AUDIO:
- Html5Capatibility._AudioClass = egret.web.WebAudioSound;
- break;
- case AudioType.HTML5_AUDIO:
- Html5Capatibility._AudioClass = egret.web.HtmlSound;
- break;
- }
- };
- /**
- * @private
- * 获取ios版本
- * @returns {string}
- */
- Html5Capatibility.getIOSVersion = function () {
- var matches = Html5Capatibility.ua.toLowerCase().match(/cpu [^\d]*\d.*like mac os x/);
- if (!matches || matches.length == 0) {
- return 0;
- }
- var value = matches[0];
- return parseInt(value.match(/\d+(_\d)*/)[0]) || 0;
- };
- //当前浏览器版本是否支持blob
- Html5Capatibility._canUseBlob = false;
- //当前浏览器版本是否支持webaudio
- Html5Capatibility._audioType = 0;
- /**
- * @private
- */
- Html5Capatibility.ua = "";
- return Html5Capatibility;
- }(egret.HashObject));
- web.Html5Capatibility = Html5Capatibility;
- __reflect(Html5Capatibility.prototype, "egret.web.Html5Capatibility");
- /**
- * @private
- */
- var currentPrefix = null;
- /**
- * @private
- */
- function getPrefixStyleName(name, element) {
- var header = "";
- if (element != null) {
- header = getPrefix(name, element);
- }
- else {
- if (currentPrefix == null) {
- var tempStyle = document.createElement('div').style;
- currentPrefix = getPrefix("transform", tempStyle);
- }
- header = currentPrefix;
- }
- if (header == "") {
- return name;
- }
- return header + name.charAt(0).toUpperCase() + name.substring(1, name.length);
- }
- web.getPrefixStyleName = getPrefixStyleName;
- /**
- * @private
- */
- function getPrefix(name, element) {
- if (name in element) {
- return "";
- }
- name = name.charAt(0).toUpperCase() + name.substring(1, name.length);
- var transArr = ["webkit", "ms", "Moz", "O"];
- for (var i = 0; i < transArr.length; i++) {
- var tempStyle = transArr[i] + name;
- if (tempStyle in element) {
- return transArr[i];
- }
- }
- return "";
- }
- web.getPrefix = getPrefix;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- * 刷新所有Egret播放器的显示区域尺寸。仅当使用外部JavaScript代码动态修改了Egret容器大小时,需要手动调用此方法刷新显示区域。
- * 当网页尺寸发生改变时此方法会自动被调用。
- */
- function updateAllScreens() {
- if (!isRunning) {
- return;
- }
- var containerList = document.querySelectorAll(".egret-player");
- var length = containerList.length;
- for (var i = 0; i < length; i++) {
- var container = containerList[i];
- var player = container["egret-player"];
- player.updateScreenSize();
- }
- }
- var isRunning = false;
- /**
- * @private
- * 网页加载完成,实例化页面中定义的Egret标签
- */
- function runEgret(options) {
- if (isRunning) {
- return;
- }
- isRunning = true;
- if (!options) {
- options = {};
- }
- var ua = navigator.userAgent.toLowerCase();
- if (ua.indexOf("egretnative") >= 0 && ua.indexOf("egretwebview") == -1) {
- egret.Capabilities["runtimeType" + ""] = egret.RuntimeType.RUNTIME2;
- }
- if (ua.indexOf("egretnative") >= 0 && egret.nativeRender) {
- egret_native.addModuleCallback(function () {
- web.Html5Capatibility.$init();
- // WebGL上下文参数自定义
- if (options.renderMode == "webgl") {
- // WebGL抗锯齿默认关闭,提升PC及某些平台性能
- var antialias = options.antialias;
- web.WebGLRenderContext.antialias = !!antialias;
- }
- egret.sys.CanvasRenderBuffer = web.CanvasRenderBuffer;
- setRenderMode(options.renderMode);
- egret_native.nrSetRenderMode(2);
- var canvasScaleFactor;
- if (options.canvasScaleFactor) {
- canvasScaleFactor = options.canvasScaleFactor;
- }
- else if (options.calculateCanvasScaleFactor) {
- canvasScaleFactor = options.calculateCanvasScaleFactor(egret.sys.canvasHitTestBuffer.context);
- }
- else {
- canvasScaleFactor = window.devicePixelRatio;
- }
- egret.sys.DisplayList.$canvasScaleFactor = canvasScaleFactor;
- var ticker = egret.ticker;
- startTicker(ticker);
- if (options.screenAdapter) {
- egret.sys.screenAdapter = options.screenAdapter;
- }
- else if (!egret.sys.screenAdapter) {
- egret.sys.screenAdapter = new egret.sys.DefaultScreenAdapter();
- }
- var list = document.querySelectorAll(".egret-player");
- var length = list.length;
- for (var i = 0; i < length; i++) {
- var container = list[i];
- var player = new web.WebPlayer(container, options);
- container["egret-player"] = player;
- }
- window.addEventListener("resize", function () {
- if (isNaN(resizeTimer)) {
- resizeTimer = window.setTimeout(doResize, 300);
- }
- });
- }, null);
- egret_native.initNativeRender();
- }
- else {
- web.Html5Capatibility._audioType = options.audioType;
- web.Html5Capatibility.$init();
- var renderMode = options.renderMode;
- // WebGL上下文参数自定义
- if (renderMode == "webgl") {
- // WebGL抗锯齿默认关闭,提升PC及某些平台性能
- var antialias = options.antialias;
- web.WebGLRenderContext.antialias = !!antialias;
- // WebGLRenderContext.antialias = (typeof antialias == undefined) ? true : antialias;
- }
- egret.sys.CanvasRenderBuffer = web.CanvasRenderBuffer;
- if (ua.indexOf("egretnative") >= 0 && renderMode != "webgl") {
- egret.$warn(1051);
- renderMode = "webgl";
- }
- setRenderMode(renderMode);
- var canvasScaleFactor = void 0;
- if (options.canvasScaleFactor) {
- canvasScaleFactor = options.canvasScaleFactor;
- }
- else if (options.calculateCanvasScaleFactor) {
- canvasScaleFactor = options.calculateCanvasScaleFactor(egret.sys.canvasHitTestBuffer.context);
- }
- else {
- //based on : https://github.com/jondavidjohn/hidpi-canvas-polyfill
- var context = egret.sys.canvasHitTestBuffer.context;
- var backingStore = context.backingStorePixelRatio ||
- context.webkitBackingStorePixelRatio ||
- context.mozBackingStorePixelRatio ||
- context.msBackingStorePixelRatio ||
- context.oBackingStorePixelRatio ||
- context.backingStorePixelRatio || 1;
- canvasScaleFactor = (window.devicePixelRatio || 1) / backingStore;
- }
- egret.sys.DisplayList.$canvasScaleFactor = canvasScaleFactor;
- var ticker_1 = egret.ticker;
- startTicker(ticker_1);
- if (options.screenAdapter) {
- egret.sys.screenAdapter = options.screenAdapter;
- }
- else if (!egret.sys.screenAdapter) {
- egret.sys.screenAdapter = new egret.sys.DefaultScreenAdapter();
- }
- var list = document.querySelectorAll(".egret-player");
- var length_2 = list.length;
- for (var i = 0; i < length_2; i++) {
- var container = list[i];
- var player = new web.WebPlayer(container, options);
- container["egret-player"] = player;
- }
- window.addEventListener("resize", function () {
- if (isNaN(resizeTimer)) {
- resizeTimer = window.setTimeout(doResize, 300);
- }
- });
- }
- }
- /**
- * 设置渲染模式。"auto","webgl","canvas"
- * @param renderMode
- */
- function setRenderMode(renderMode) {
- if (renderMode == "webgl" && egret.WebGLUtils.checkCanUseWebGL()) {
- egret.sys.RenderBuffer = web.WebGLRenderBuffer;
- egret.sys.systemRenderer = new web.WebGLRenderer();
- egret.sys.canvasRenderer = new egret.CanvasRenderer();
- egret.sys.customHitTestBuffer = new web.WebGLRenderBuffer(3, 3);
- egret.sys.canvasHitTestBuffer = new web.CanvasRenderBuffer(3, 3);
- egret.Capabilities["renderMode" + ""] = "webgl";
- }
- else {
- egret.sys.RenderBuffer = web.CanvasRenderBuffer;
- egret.sys.systemRenderer = new egret.CanvasRenderer();
- egret.sys.canvasRenderer = egret.sys.systemRenderer;
- egret.sys.customHitTestBuffer = new web.CanvasRenderBuffer(3, 3);
- egret.sys.canvasHitTestBuffer = egret.sys.customHitTestBuffer;
- egret.Capabilities["renderMode" + ""] = "canvas";
- }
- }
- /**
- * @private
- * 启动心跳计时器。
- */
- function startTicker(ticker) {
- var requestAnimationFrame = window["requestAnimationFrame"] ||
- window["webkitRequestAnimationFrame"] ||
- window["mozRequestAnimationFrame"] ||
- window["oRequestAnimationFrame"] ||
- window["msRequestAnimationFrame"];
- if (!requestAnimationFrame) {
- requestAnimationFrame = function (callback) {
- return window.setTimeout(callback, 1000 / 60);
- };
- }
- requestAnimationFrame(onTick);
- function onTick() {
- ticker.update();
- requestAnimationFrame(onTick);
- }
- }
- //覆盖原生的isNaN()方法实现,在不同浏览器上有2~10倍性能提升。
- window["isNaN"] = function (value) {
- value = +value;
- return value !== value;
- };
- egret.runEgret = runEgret;
- egret.updateAllScreens = updateAllScreens;
- var resizeTimer = NaN;
- function doResize() {
- resizeTimer = NaN;
- egret.updateAllScreens();
- }
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- if (true) {
- var language = navigator.language || navigator["browserLanguage"] || "en_US";
- language = language.replace("-", "_");
- if (language in egret.$locale_strings)
- egret.$language = language;
- }
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var WebCapability = (function () {
- function WebCapability() {
- }
- /**
- * @private
- * 检测系统属性
- */
- WebCapability.detect = function () {
- var capabilities = egret.Capabilities;
- var ua = navigator.userAgent.toLowerCase();
- capabilities["isMobile" + ""] = (ua.indexOf('mobile') != -1 || ua.indexOf('android') != -1);
- if (capabilities.isMobile) {
- if (ua.indexOf("windows") < 0 && (ua.indexOf("iphone") != -1 || ua.indexOf("ipad") != -1 || ua.indexOf("ipod") != -1)) {
- capabilities["os" + ""] = "iOS";
- }
- else if (ua.indexOf("android") != -1 && ua.indexOf("linux") != -1) {
- capabilities["os" + ""] = "Android";
- }
- else if (ua.indexOf("windows") != -1) {
- capabilities["os" + ""] = "Windows Phone";
- }
- }
- else {
- if (ua.indexOf("windows nt") != -1) {
- capabilities["os" + ""] = "Windows PC";
- }
- else if (ua.indexOf("mac os") != -1) {
- capabilities["os" + ""] = "Mac OS";
- }
- }
- var language = (navigator.language || navigator["browserLanguage"]).toLowerCase();
- var strings = language.split("-");
- if (strings.length > 1) {
- strings[1] = strings[1].toUpperCase();
- }
- capabilities["language" + ""] = strings.join("-");
- WebCapability.injectUIntFixOnIE9();
- };
- WebCapability.injectUIntFixOnIE9 = function () {
- if (/msie 9.0/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
- var IEBinaryToArray_ByteStr_Script = "<!-- IEBinaryToArray_ByteStr -->\r\n" +
- "<script type='text/vbscript' language='VBScript'>\r\n" +
- "Function IEBinaryToArray_ByteStr(Binary)\r\n" +
- " IEBinaryToArray_ByteStr = CStr(Binary)\r\n" +
- "End Function\r\n" +
- "Function IEBinaryToArray_ByteStr_Last(Binary)\r\n" +
- " Dim lastIndex\r\n" +
- " lastIndex = LenB(Binary)\r\n" +
- " if lastIndex mod 2 Then\r\n" +
- " IEBinaryToArray_ByteStr_Last = Chr( AscB( MidB( Binary, lastIndex, 1 ) ) )\r\n" +
- " Else\r\n" +
- " IEBinaryToArray_ByteStr_Last = " + '""' + "\r\n" +
- " End If\r\n" +
- "End Function\r\n" + "<\/script>\r\n" +
- "<!-- convertResponseBodyToText -->\r\n" +
- "<script>\r\n" +
- "let convertResponseBodyToText = function (binary) {\r\n" +
- " let byteMapping = {};\r\n" +
- " for ( let i = 0; i < 256; i++ ) {\r\n" +
- " for ( let j = 0; j < 256; j++ ) {\r\n" +
- " byteMapping[ String.fromCharCode( i + j * 256 ) ] =\r\n" +
- " String.fromCharCode(i) + String.fromCharCode(j);\r\n" +
- " }\r\n" +
- " }\r\n" +
- " let rawBytes = IEBinaryToArray_ByteStr(binary);\r\n" +
- " let lastChr = IEBinaryToArray_ByteStr_Last(binary);\r\n" +
- " return rawBytes.replace(/[\\s\\S]/g," +
- " function( match ) { return byteMapping[match]; }) + lastChr;\r\n" +
- "};\r\n" +
- "<\/script>\r\n";
- document.write(IEBinaryToArray_ByteStr_Script);
- }
- };
- return WebCapability;
- }());
- web.WebCapability = WebCapability;
- __reflect(WebCapability.prototype, "egret.web.WebCapability");
- WebCapability.detect();
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var WebFps = (function () {
- function WebFps(stage, showFPS, showLog, logFilter, styles) {
- this.showPanle = true;
- this.fpsHeight = 0;
- this.WIDTH = 101;
- this.HEIGHT = 20;
- this.bgCanvasColor = "#18304b";
- this.fpsFrontColor = "#18fefe";
- this.WIDTH_COST = 50;
- this.cost1Color = "#18fefe";
- // private cost2Color = "#ffff00";
- this.cost3Color = "#ff0000";
- this.arrFps = [];
- this.arrCost = [];
- this.arrLog = [];
- if (showFPS || showLog) {
- if (egret.Capabilities.renderMode == 'canvas') {
- this.renderMode = "Canvas";
- }
- else {
- this.renderMode = "WebGL";
- }
- this.panelX = styles["x"] === undefined ? 0 : parseInt(styles['x']);
- this.panelY = styles["y"] === undefined ? 0 : parseInt(styles['y']);
- this.fontColor = styles["textColor"] === undefined ? '#ffffff' : styles['textColor'].replace("0x", "#");
- this.fontSize = styles["size"] === undefined ? 12 : parseInt(styles['size']);
- if (egret.Capabilities.isMobile) {
- this.fontSize -= 2;
- }
- var all = document.createElement('div');
- all.style.position = 'absolute';
- all.style.background = "rgba(0,0,0," + styles['bgAlpha'] + ")";
- all.style.left = this.panelX + 'px';
- all.style.top = this.panelY + 'px';
- all.style.pointerEvents = 'none';
- document.body.appendChild(all);
- var container = document.createElement('div');
- container.style.color = this.fontColor;
- container.style.fontSize = this.fontSize + 'px';
- container.style.lineHeight = this.fontSize + 'px';
- container.style.margin = '4px 4px 4px 4px';
- this.container = container;
- all.appendChild(container);
- if (showFPS)
- this.addFps();
- if (showLog)
- this.addLog();
- }
- }
- WebFps.prototype.addFps = function () {
- var div = document.createElement('div');
- div.style.display = 'inline-block';
- this.containerFps = div;
- this.container.appendChild(div);
- var fps = document.createElement('div');
- fps.style.paddingBottom = '2px';
- this.fps = fps;
- this.containerFps.appendChild(fps);
- fps.innerHTML = "0 FPS " + this.renderMode + "<br/>min0 max0 avg0";
- var canvas = document.createElement('canvas');
- this.containerFps.appendChild(canvas);
- canvas.width = this.WIDTH;
- canvas.height = this.HEIGHT;
- this.canvasFps = canvas;
- var context = canvas.getContext('2d');
- this.contextFps = context;
- context.fillStyle = this.bgCanvasColor;
- context.fillRect(0, 0, this.WIDTH, this.HEIGHT);
- var divDatas = document.createElement('div');
- this.divDatas = divDatas;
- this.containerFps.appendChild(divDatas);
- var left = document.createElement('div');
- left.style['float'] = 'left';
- left.innerHTML = "Draw<br/>Cost";
- divDatas.appendChild(left);
- var right = document.createElement('div');
- right.style.paddingLeft = left.offsetWidth + 20 + "px";
- divDatas.appendChild(right);
- var draw = document.createElement('div');
- this.divDraw = draw;
- draw.innerHTML = "0<br/>";
- right.appendChild(draw);
- var cost = document.createElement('div');
- this.divCost = cost;
- cost.innerHTML = "<font style=\"color:" + this.cost1Color + "\">0<font/> <font style=\"color:" + this.cost3Color + "\">0<font/>";
- right.appendChild(cost);
- canvas = document.createElement('canvas');
- this.canvasCost = canvas;
- this.containerFps.appendChild(canvas);
- canvas.width = this.WIDTH;
- canvas.height = this.HEIGHT;
- context = canvas.getContext('2d');
- this.contextCost = context;
- context.fillStyle = this.bgCanvasColor;
- context.fillRect(0, 0, this.WIDTH, this.HEIGHT);
- context.fillStyle = "#000000";
- context.fillRect(this.WIDTH_COST, 0, 1, this.HEIGHT);
- this.fpsHeight = this.container.offsetHeight;
- };
- WebFps.prototype.addLog = function () {
- var log = document.createElement('div');
- log.style.maxWidth = document.body.clientWidth - 8 - this.panelX + 'px';
- log.style.wordWrap = "break-word";
- this.log = log;
- this.container.appendChild(log);
- };
- WebFps.prototype.update = function (datas, showLastData) {
- if (showLastData === void 0) { showLastData = false; }
- var numFps;
- var numCostTicker;
- var numCostRender;
- if (!showLastData) {
- numFps = datas.fps;
- numCostTicker = datas.costTicker;
- numCostRender = datas.costRender;
- this.lastNumDraw = datas.draw;
- this.arrFps.push(numFps);
- this.arrCost.push([numCostTicker, numCostRender]);
- }
- else {
- numFps = this.arrFps[this.arrFps.length - 1];
- numCostTicker = this.arrCost[this.arrCost.length - 1][0];
- numCostRender = this.arrCost[this.arrCost.length - 1][1];
- }
- var fpsTotal = 0;
- var lenFps = this.arrFps.length;
- if (lenFps > 101) {
- lenFps = 101;
- this.arrFps.shift();
- this.arrCost.shift();
- }
- var fpsMin = this.arrFps[0];
- var fpsMax = this.arrFps[0];
- for (var i = 0; i < lenFps; i++) {
- var num = this.arrFps[i];
- fpsTotal += num;
- if (num < fpsMin)
- fpsMin = num;
- else if (num > fpsMax)
- fpsMax = num;
- }
- var WIDTH = this.WIDTH;
- var HEIGHT = this.HEIGHT;
- var context = this.contextFps;
- context.drawImage(this.canvasFps, 1, 0, WIDTH - 1, HEIGHT, 0, 0, WIDTH - 1, HEIGHT);
- context.fillStyle = this.bgCanvasColor;
- context.fillRect(WIDTH - 1, 0, 1, HEIGHT);
- var lastHeight = Math.floor(numFps / 60 * 20);
- if (lastHeight < 1)
- lastHeight = 1;
- context.fillStyle = this.fpsFrontColor;
- context.fillRect(WIDTH - 1, 20 - lastHeight, 1, lastHeight);
- var WIDTH_COST = this.WIDTH_COST;
- context = this.contextCost;
- context.drawImage(this.canvasCost, 1, 0, WIDTH_COST - 1, HEIGHT, 0, 0, WIDTH_COST - 1, HEIGHT);
- context.drawImage(this.canvasCost, WIDTH_COST + 2, 0, WIDTH_COST - 1, HEIGHT, WIDTH_COST + 1, 0, WIDTH_COST - 1, HEIGHT);
- var c1Height = Math.floor(numCostTicker / 2);
- if (c1Height < 1)
- c1Height = 1;
- else if (c1Height > 20)
- c1Height = 20;
- //todo lcj
- var c2Height = Math.floor(numCostRender / 2);
- if (c2Height < 1)
- c2Height = 1;
- else if (c2Height > 20)
- c2Height = 20;
- context.fillStyle = this.bgCanvasColor;
- context.fillRect(WIDTH_COST - 1, 0, 1, HEIGHT);
- context.fillRect(WIDTH_COST * 2, 0, 1, HEIGHT);
- context.fillRect(WIDTH_COST * 3 + 1, 0, 1, HEIGHT);
- context.fillStyle = this.cost1Color;
- context.fillRect(WIDTH_COST - 1, 20 - c1Height, 1, c1Height);
- context.fillStyle = this.cost3Color;
- context.fillRect(WIDTH_COST * 2, 20 - c2Height, 1, c2Height);
- var fpsAvg = Math.floor(fpsTotal / lenFps);
- var fpsOutput = numFps + " FPS " + this.renderMode;
- if (this.showPanle) {
- fpsOutput += "<br/>min" + fpsMin + " max" + fpsMax + " avg" + fpsAvg;
- this.divDraw.innerHTML = this.lastNumDraw + "<br/>";
- this.divCost.innerHTML = "<font style=\"color:#18fefe\">" + numCostTicker + "<font/> <font style=\"color:#ff0000\">" + numCostRender + "<font/>";
- }
- this.fps.innerHTML = fpsOutput;
- };
- ;
- WebFps.prototype.updateInfo = function (info) {
- this.arrLog.push(info);
- this.updateLogLayout();
- };
- WebFps.prototype.updateWarn = function (info) {
- this.arrLog.push("[Warning]" + info);
- this.updateLogLayout();
- };
- WebFps.prototype.updateError = function (info) {
- this.arrLog.push("[Error]" + info);
- this.updateLogLayout();
- };
- WebFps.prototype.updateLogLayout = function () {
- this.log.innerHTML = this.arrLog.join('<br/>');
- while (document.body.clientHeight < (this.log.offsetHeight + this.fpsHeight + this.panelY + this.fontSize * 2)) {
- this.arrLog.shift();
- this.log.innerHTML = this.arrLog.join('<br/>');
- }
- };
- return WebFps;
- }());
- web.WebFps = WebFps;
- __reflect(WebFps.prototype, "egret.web.WebFps", ["egret.FPSDisplay"]);
- egret.FPSDisplay = WebFps;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var localStorage;
- (function (localStorage) {
- var web;
- (function (web) {
- /**
- * @private
- *
- * @param key
- * @returns
- */
- function getItem(key) {
- return window.localStorage.getItem(key);
- }
- /**
- * @private
- *
- * @param key
- * @param value
- * @returns
- */
- function setItem(key, value) {
- try {
- window.localStorage.setItem(key, value);
- return true;
- }
- catch (e) {
- egret.$warn(1047, key, value);
- return false;
- }
- }
- /**
- * @private
- *
- * @param key
- */
- function removeItem(key) {
- window.localStorage.removeItem(key);
- }
- /**
- * @private
- *
- */
- function clear() {
- window.localStorage.clear();
- }
- localStorage.getItem = getItem;
- localStorage.setItem = setItem;
- localStorage.removeItem = removeItem;
- localStorage.clear = clear;
- })(web = localStorage.web || (localStorage.web = {}));
- })(localStorage = egret.localStorage || (egret.localStorage = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var WebPlayer = (function (_super) {
- __extends(WebPlayer, _super);
- function WebPlayer(container, options) {
- var _this = _super.call(this) || this;
- _this.init(container, options);
- _this.initOrientation();
- return _this;
- }
- WebPlayer.prototype.init = function (container, options) {
- var option = this.readOption(container, options);
- var stage = new egret.Stage();
- stage.$screen = this;
- stage.$scaleMode = option.scaleMode;
- stage.$orientation = option.orientation;
- stage.$maxTouches = option.maxTouches;
- stage.frameRate = option.frameRate;
- stage.textureScaleFactor = option.textureScaleFactor;
- var buffer = new egret.sys.RenderBuffer(undefined, undefined, true);
- var canvas = buffer.surface;
- this.attachCanvas(container, canvas);
- var webTouch = new web.WebTouchHandler(stage, canvas);
- var player = new egret.sys.Player(buffer, stage, option.entryClassName);
- egret.lifecycle.stage = stage;
- egret.lifecycle.addLifecycleListener(web.WebLifeCycleHandler);
- var webInput = new web.HTMLInput();
- if (option.showFPS || option.showLog) {
- if (!egret.nativeRender) {
- player.displayFPS(option.showFPS, option.showLog, option.logFilter, option.fpsStyles);
- }
- }
- this.playerOption = option;
- this.container = container;
- this.canvas = canvas;
- this.stage = stage;
- this.player = player;
- this.webTouchHandler = webTouch;
- this.webInput = webInput;
- egret.web.$cacheTextAdapter(webInput, stage, container, canvas);
- this.updateScreenSize();
- this.updateMaxTouches();
- player.start();
- };
- WebPlayer.prototype.initOrientation = function () {
- var self = this;
- window.addEventListener("orientationchange", function () {
- window.setTimeout(function () {
- egret.StageOrientationEvent.dispatchStageOrientationEvent(self.stage, egret.StageOrientationEvent.ORIENTATION_CHANGE);
- }, 350);
- });
- };
- /**
- * 读取初始化参数
- */
- WebPlayer.prototype.readOption = function (container, options) {
- var option = {};
- option.entryClassName = container.getAttribute("data-entry-class");
- option.scaleMode = container.getAttribute("data-scale-mode") || egret.StageScaleMode.NO_SCALE;
- option.frameRate = +container.getAttribute("data-frame-rate") || 30;
- option.contentWidth = +container.getAttribute("data-content-width") || 480;
- option.contentHeight = +container.getAttribute("data-content-height") || 800;
- option.orientation = container.getAttribute("data-orientation") || egret.OrientationMode.AUTO;
- option.maxTouches = +container.getAttribute("data-multi-fingered") || 2;
- option.textureScaleFactor = +container.getAttribute("texture-scale-factor") || 1;
- option.showFPS = container.getAttribute("data-show-fps") == "true";
- var styleStr = container.getAttribute("data-show-fps-style") || "";
- var stylesArr = styleStr.split(",");
- var styles = {};
- for (var i = 0; i < stylesArr.length; i++) {
- var tempStyleArr = stylesArr[i].split(":");
- styles[tempStyleArr[0]] = tempStyleArr[1];
- }
- option.fpsStyles = styles;
- option.showLog = container.getAttribute("data-show-log") == "true";
- option.logFilter = container.getAttribute("data-log-filter");
- return option;
- };
- /**
- * @private
- * 添加canvas到container。
- */
- WebPlayer.prototype.attachCanvas = function (container, canvas) {
- var style = canvas.style;
- style.cursor = "inherit";
- style.position = "absolute";
- style.top = "0";
- style.bottom = "0";
- style.left = "0";
- style.right = "0";
- container.appendChild(canvas);
- style = container.style;
- style.overflow = "hidden";
- style.position = "absolute";
- };
- /**
- * @private
- * 更新播放器视口尺寸
- */
- WebPlayer.prototype.updateScreenSize = function () {
- var canvas = this.canvas;
- if (canvas['userTyping'])
- return;
- var option = this.playerOption;
- var screenRect = this.container.getBoundingClientRect();
- var top = 0;
- var boundingClientWidth = screenRect.width;
- var boundingClientHeight = screenRect.height;
- if (boundingClientWidth == 0 || boundingClientHeight == 0) {
- return;
- }
- if (screenRect.top < 0) {
- boundingClientHeight += screenRect.top;
- top = -screenRect.top;
- }
- var shouldRotate = false;
- var orientation = this.stage.$orientation;
- if (orientation != egret.OrientationMode.AUTO) {
- shouldRotate = orientation != egret.OrientationMode.PORTRAIT && boundingClientHeight > boundingClientWidth
- || orientation == egret.OrientationMode.PORTRAIT && boundingClientWidth > boundingClientHeight;
- }
- var screenWidth = shouldRotate ? boundingClientHeight : boundingClientWidth;
- var screenHeight = shouldRotate ? boundingClientWidth : boundingClientHeight;
- egret.Capabilities["boundingClientWidth" + ""] = screenWidth;
- egret.Capabilities["boundingClientHeight" + ""] = screenHeight;
- var stageSize = egret.sys.screenAdapter.calculateStageSize(this.stage.$scaleMode, screenWidth, screenHeight, option.contentWidth, option.contentHeight);
- var stageWidth = stageSize.stageWidth;
- var stageHeight = stageSize.stageHeight;
- var displayWidth = stageSize.displayWidth;
- var displayHeight = stageSize.displayHeight;
- canvas.style[egret.web.getPrefixStyleName("transformOrigin")] = "0% 0% 0px";
- if (canvas.width != stageWidth) {
- canvas.width = stageWidth;
- }
- if (canvas.height != stageHeight) {
- canvas.height = stageHeight;
- }
- var rotation = 0;
- if (shouldRotate) {
- if (orientation == egret.OrientationMode.LANDSCAPE) {
- rotation = 90;
- canvas.style.top = top + (boundingClientHeight - displayWidth) / 2 + "px";
- canvas.style.left = (boundingClientWidth + displayHeight) / 2 + "px";
- }
- else {
- rotation = -90;
- canvas.style.top = top + (boundingClientHeight + displayWidth) / 2 + "px";
- canvas.style.left = (boundingClientWidth - displayHeight) / 2 + "px";
- }
- }
- else {
- canvas.style.top = top + (boundingClientHeight - displayHeight) / 2 + "px";
- canvas.style.left = (boundingClientWidth - displayWidth) / 2 + "px";
- }
- var scalex = displayWidth / stageWidth, scaley = displayHeight / stageHeight;
- var canvasScaleX = scalex * egret.sys.DisplayList.$canvasScaleFactor;
- var canvasScaleY = scaley * egret.sys.DisplayList.$canvasScaleFactor;
- if (egret.Capabilities.renderMode == "canvas") {
- canvasScaleX = Math.ceil(canvasScaleX);
- canvasScaleY = Math.ceil(canvasScaleY);
- }
- var m = egret.Matrix.create();
- m.identity();
- m.scale(scalex / canvasScaleX, scaley / canvasScaleY);
- m.rotate(rotation * Math.PI / 180);
- var transform = "matrix(" + m.a + "," + m.b + "," + m.c + "," + m.d + "," + m.tx + "," + m.ty + ")";
- egret.Matrix.release(m);
- canvas.style[egret.web.getPrefixStyleName("transform")] = transform;
- egret.sys.DisplayList.$setCanvasScale(canvasScaleX, canvasScaleY);
- this.webTouchHandler.updateScaleMode(scalex, scaley, rotation);
- this.webInput.$updateSize();
- this.player.updateStageSize(stageWidth, stageHeight); //不要在这个方法后面修改属性
- // todo
- if (egret.nativeRender) {
- canvas.width = stageWidth * canvasScaleX;
- canvas.height = stageHeight * canvasScaleY;
- }
- };
- WebPlayer.prototype.setContentSize = function (width, height) {
- var option = this.playerOption;
- option.contentWidth = width;
- option.contentHeight = height;
- this.updateScreenSize();
- };
- /**
- * @private
- * 更新触摸数量
- */
- WebPlayer.prototype.updateMaxTouches = function () {
- this.webTouchHandler.$updateMaxTouches();
- };
- return WebPlayer;
- }(egret.HashObject));
- web.WebPlayer = WebPlayer;
- __reflect(WebPlayer.prototype, "egret.web.WebPlayer", ["egret.sys.Screen"]);
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- var sharedCanvas;
- var sharedContext;
- /**
- * @private
- */
- function convertImageToCanvas(texture, rect) {
- if (!sharedCanvas) {
- sharedCanvas = document.createElement("canvas");
- sharedContext = sharedCanvas.getContext("2d");
- }
- var w = texture.$getTextureWidth();
- var h = texture.$getTextureHeight();
- if (rect == null) {
- rect = egret.$TempRectangle;
- rect.x = 0;
- rect.y = 0;
- rect.width = w;
- rect.height = h;
- }
- rect.x = Math.min(rect.x, w - 1);
- rect.y = Math.min(rect.y, h - 1);
- rect.width = Math.min(rect.width, w - rect.x);
- rect.height = Math.min(rect.height, h - rect.y);
- var iWidth = rect.width;
- var iHeight = rect.height;
- var surface = sharedCanvas;
- surface["style"]["width"] = iWidth + "px";
- surface["style"]["height"] = iHeight + "px";
- sharedCanvas.width = iWidth;
- sharedCanvas.height = iHeight;
- if (egret.Capabilities.renderMode == "webgl") {
- var renderTexture = void 0;
- //webgl下非RenderTexture纹理先画到RenderTexture
- if (!texture.$renderBuffer) {
- renderTexture = new egret.RenderTexture();
- renderTexture.drawToTexture(new egret.Bitmap(texture));
- }
- else {
- renderTexture = texture;
- }
- //从RenderTexture中读取像素数据,填入canvas
- var pixels = renderTexture.$renderBuffer.getPixels(rect.x, rect.y, iWidth, iHeight);
- var imageData = new ImageData(iWidth, iHeight);
- for (var i = 0; i < pixels.length; i++) {
- imageData.data[i] = pixels[i];
- }
- sharedContext.putImageData(imageData, 0, 0);
- if (!texture.$renderBuffer) {
- renderTexture.dispose();
- }
- return surface;
- }
- else {
- var bitmapData = texture;
- var offsetX = Math.round(bitmapData.$offsetX);
- var offsetY = Math.round(bitmapData.$offsetY);
- var bitmapWidth = bitmapData.$bitmapWidth;
- var bitmapHeight = bitmapData.$bitmapHeight;
- sharedContext.drawImage(bitmapData.$bitmapData.source, bitmapData.$bitmapX + rect.x / egret.$TextureScaleFactor, bitmapData.$bitmapY + rect.y / egret.$TextureScaleFactor, bitmapWidth * rect.width / w, bitmapHeight * rect.height / h, offsetX, offsetY, rect.width, rect.height);
- return surface;
- }
- }
- /**
- * @private
- */
- function toDataURL(type, rect, encoderOptions) {
- try {
- var surface = convertImageToCanvas(this, rect);
- var result = surface.toDataURL(type, encoderOptions);
- return result;
- }
- catch (e) {
- egret.$error(1033);
- }
- return null;
- }
- /**
- * 有些杀毒软件认为 saveToFile 可能是一个病毒文件
- */
- function eliFoTevas(type, filePath, rect, encoderOptions) {
- var base64 = toDataURL.call(this, type, rect, encoderOptions);
- if (base64 == null) {
- return;
- }
- var href = base64.replace(/^data:image[^;]*/, "data:image/octet-stream");
- var aLink = document.createElement('a');
- aLink['download'] = filePath;
- aLink.href = href;
- var evt = document.createEvent('MouseEvents');
- evt.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
- aLink.dispatchEvent(evt);
- }
- function getPixel32(x, y) {
- egret.$warn(1041, "getPixel32", "getPixels");
- return this.getPixels(x, y);
- }
- function getPixels(x, y, width, height) {
- if (width === void 0) { width = 1; }
- if (height === void 0) { height = 1; }
- //webgl环境下不需要转换成canvas获取像素信息
- if (egret.Capabilities.renderMode == "webgl") {
- var renderTexture = void 0;
- //webgl下非RenderTexture纹理先画到RenderTexture
- if (!this.$renderBuffer) {
- renderTexture = new egret.RenderTexture();
- renderTexture.drawToTexture(new egret.Bitmap(this));
- }
- else {
- renderTexture = this;
- }
- //从RenderTexture中读取像素数据
- var pixels = renderTexture.$renderBuffer.getPixels(x, y, width, height);
- return pixels;
- }
- try {
- var surface = convertImageToCanvas(this);
- var result = sharedContext.getImageData(x, y, width, height).data;
- return result;
- }
- catch (e) {
- egret.$error(1039);
- }
- }
- egret.Texture.prototype.toDataURL = toDataURL;
- egret.Texture.prototype.saveToFile = eliFoTevas;
- egret.Texture.prototype.getPixel32 = getPixel32;
- egret.Texture.prototype.getPixels = getPixels;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- * XML节点基类
- */
- var XMLNode = (function () {
- /**
- * @private
- */
- function XMLNode(nodeType, parent) {
- this.nodeType = nodeType;
- this.parent = parent;
- }
- return XMLNode;
- }());
- web.XMLNode = XMLNode;
- __reflect(XMLNode.prototype, "egret.web.XMLNode");
- /**
- * @private
- * XML节点对象
- */
- var XML = (function (_super) {
- __extends(XML, _super);
- /**
- * @private
- */
- function XML(localName, parent, prefix, namespace, name) {
- var _this = _super.call(this, 1, parent) || this;
- /**
- * @private
- * 当前节点上的属性列表
- */
- _this.attributes = {};
- /**
- * @private
- * 当前节点的子节点列表
- */
- _this.children = [];
- _this.localName = localName;
- _this.prefix = prefix;
- _this.namespace = namespace;
- _this.name = name;
- return _this;
- }
- return XML;
- }(XMLNode));
- web.XML = XML;
- __reflect(XML.prototype, "egret.web.XML");
- /**
- * @private
- * XML文本节点
- */
- var XMLText = (function (_super) {
- __extends(XMLText, _super);
- /**
- * @private
- */
- function XMLText(text, parent) {
- var _this = _super.call(this, 3, parent) || this;
- _this.text = text;
- return _this;
- }
- return XMLText;
- }(XMLNode));
- web.XMLText = XMLText;
- __reflect(XMLText.prototype, "egret.web.XMLText");
- var parser = new DOMParser();
- /**
- * @private
- * 解析字符串为XML对象
- * @param text 要解析的字符串
- */
- function parse(text) {
- var xmlDoc = parser.parseFromString(text, "text/xml");
- var length = xmlDoc.childNodes.length;
- for (var i = 0; i < length; i++) {
- var node = xmlDoc.childNodes[i];
- if (node.nodeType == 1) {
- return parseNode(node, null);
- }
- }
- return null;
- }
- /**
- * @private
- * 解析一个节点
- */
- function parseNode(node, parent) {
- if (node.localName == "parsererror") {
- throw new Error(node.textContent);
- }
- var xml = new XML(node.localName, parent, node["prefix"], node.namespaceURI, node.nodeName);
- var nodeAttributes = node.attributes;
- var attributes = xml.attributes;
- var length = nodeAttributes.length;
- for (var i = 0; i < length; i++) {
- var attributeNode = nodeAttributes[i];
- var name_1 = attributeNode.name;
- if (name_1.indexOf("xmlns:") == 0) {
- continue;
- }
- attributes[name_1] = attributeNode.value;
- xml["$" + name_1] = attributeNode.value;
- }
- var childNodes = node.childNodes;
- length = childNodes.length;
- var children = xml.children;
- for (var i = 0; i < length; i++) {
- var childNode = childNodes[i];
- var nodeType = childNode.nodeType;
- var childXML = null;
- if (nodeType == 1) {
- childXML = parseNode(childNode, xml);
- }
- else if (nodeType == 3) {
- var text = childNode.textContent.trim();
- if (text) {
- childXML = new XMLText(text, xml);
- }
- }
- if (childXML) {
- children.push(childXML);
- }
- }
- return xml;
- }
- egret.XML = { parse: parse };
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var WebDeviceOrientation = (function (_super) {
- __extends(WebDeviceOrientation, _super);
- function WebDeviceOrientation() {
- var _this = _super !== null && _super.apply(this, arguments) || this;
- /**
- * @private
- */
- _this.onChange = function (e) {
- var event = new egret.OrientationEvent(egret.Event.CHANGE);
- event.beta = e.beta;
- event.gamma = e.gamma;
- event.alpha = e.alpha;
- _this.dispatchEvent(event);
- };
- return _this;
- }
- /**
- * @private
- *
- */
- WebDeviceOrientation.prototype.start = function () {
- window.addEventListener("deviceorientation", this.onChange);
- };
- /**
- * @private
- *
- */
- WebDeviceOrientation.prototype.stop = function () {
- window.removeEventListener("deviceorientation", this.onChange);
- };
- return WebDeviceOrientation;
- }(egret.EventDispatcher));
- web.WebDeviceOrientation = WebDeviceOrientation;
- __reflect(WebDeviceOrientation.prototype, "egret.web.WebDeviceOrientation", ["egret.DeviceOrientation"]);
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- egret.DeviceOrientation = egret.web.WebDeviceOrientation;
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var WebGeolocation = (function (_super) {
- __extends(WebGeolocation, _super);
- /**
- * @private
- */
- function WebGeolocation(option) {
- var _this = _super.call(this) || this;
- /**
- * @private
- */
- _this.onUpdate = function (position) {
- var event = new egret.GeolocationEvent(egret.Event.CHANGE);
- var coords = position.coords;
- event.altitude = coords.altitude;
- event.heading = coords.heading;
- event.accuracy = coords.accuracy;
- event.latitude = coords.latitude;
- event.longitude = coords.longitude;
- event.speed = coords.speed;
- event.altitudeAccuracy = coords.altitudeAccuracy;
- _this.dispatchEvent(event);
- };
- /**
- * @private
- */
- _this.onError = function (error) {
- var errorType = egret.GeolocationEvent.UNAVAILABLE;
- if (error.code == error.PERMISSION_DENIED)
- errorType = egret.GeolocationEvent.PERMISSION_DENIED;
- var event = new egret.GeolocationEvent(egret.IOErrorEvent.IO_ERROR);
- event.errorType = errorType;
- event.errorMessage = error.message;
- _this.dispatchEvent(event);
- };
- _this.geolocation = navigator.geolocation;
- return _this;
- }
- /**
- * @private
- *
- */
- WebGeolocation.prototype.start = function () {
- var geo = this.geolocation;
- if (geo)
- this.watchId = geo.watchPosition(this.onUpdate, this.onError);
- else
- this.onError({
- code: 2,
- message: egret.sys.tr(3004),
- PERMISSION_DENIED: 1,
- POSITION_UNAVAILABLE: 2
- });
- };
- /**
- * @private
- *
- */
- WebGeolocation.prototype.stop = function () {
- var geo = this.geolocation;
- geo.clearWatch(this.watchId);
- };
- return WebGeolocation;
- }(egret.EventDispatcher));
- web.WebGeolocation = WebGeolocation;
- __reflect(WebGeolocation.prototype, "egret.web.WebGeolocation", ["egret.Geolocation"]);
- egret.Geolocation = egret.web.WebGeolocation;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var WebMotion = (function (_super) {
- __extends(WebMotion, _super);
- function WebMotion() {
- var _this = _super !== null && _super.apply(this, arguments) || this;
- /**
- * @private
- */
- _this.onChange = function (e) {
- var event = new egret.MotionEvent(egret.Event.CHANGE);
- var acceleration = {
- x: e.acceleration.x,
- y: e.acceleration.y,
- z: e.acceleration.z
- };
- var accelerationIncludingGravity = {
- x: e.accelerationIncludingGravity.x,
- y: e.accelerationIncludingGravity.y,
- z: e.accelerationIncludingGravity.z
- };
- var rotation = {
- alpha: e.rotationRate.alpha,
- beta: e.rotationRate.beta,
- gamma: e.rotationRate.gamma
- };
- event.acceleration = acceleration;
- event.accelerationIncludingGravity = accelerationIncludingGravity;
- event.rotationRate = rotation;
- _this.dispatchEvent(event);
- };
- return _this;
- }
- /**
- * @private
- *
- */
- WebMotion.prototype.start = function () {
- window.addEventListener("devicemotion", this.onChange);
- };
- /**
- * @private
- *
- */
- WebMotion.prototype.stop = function () {
- window.removeEventListener("devicemotion", this.onChange);
- };
- return WebMotion;
- }(egret.EventDispatcher));
- web.WebMotion = WebMotion;
- __reflect(WebMotion.prototype, "egret.web.WebMotion", ["egret.Motion"]);
- egret.Motion = egret.web.WebMotion;
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- if (true) {
- var logFuncs_1;
- function setLogLevel(logType) {
- if (logFuncs_1 == null) {
- logFuncs_1 = {
- "error": console.error,
- "debug": console.debug,
- "warn": console.warn,
- "info": console.info,
- "log": console.log
- };
- }
- switch (logType) {
- case egret.Logger.OFF:
- console.error = function () {
- };
- case egret.Logger.ERROR:
- console.warn = function () {
- };
- case egret.Logger.WARN:
- console.info = function () {
- };
- console.log = function () {
- };
- case egret.Logger.INFO:
- console.debug = function () {
- };
- default:
- break;
- }
- switch (logType) {
- case egret.Logger.ALL:
- case egret.Logger.DEBUG:
- console.debug = logFuncs_1["debug"];
- case egret.Logger.INFO:
- console.log = logFuncs_1["log"];
- console.info = logFuncs_1["info"];
- case egret.Logger.WARN:
- console.warn = logFuncs_1["warn"];
- case egret.Logger.ERROR:
- console.error = logFuncs_1["error"];
- default:
- break;
- }
- }
- Object.defineProperty(egret.Logger, "logLevel", {
- set: setLogLevel,
- enumerable: true,
- configurable: true
- });
- }
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- * 绘制指令管理器
- * 用来维护drawData数组
- */
- var WebGLDrawCmdManager = (function () {
- function WebGLDrawCmdManager() {
- /**
- * 用于缓存绘制命令的数组
- */
- this.drawData = [];
- this.drawDataLen = 0;
- }
- /**
- * 压入绘制矩形指令
- */
- WebGLDrawCmdManager.prototype.pushDrawRect = function () {
- if (this.drawDataLen == 0 || this.drawData[this.drawDataLen - 1].type != 1 /* RECT */) {
- var data = this.drawData[this.drawDataLen] || {};
- data.type = 1 /* RECT */;
- data.count = 0;
- this.drawData[this.drawDataLen] = data;
- this.drawDataLen++;
- }
- this.drawData[this.drawDataLen - 1].count += 2;
- };
- /**
- * 压入绘制texture指令
- */
- WebGLDrawCmdManager.prototype.pushDrawTexture = function (texture, count, filter, textureWidth, textureHeight) {
- if (count === void 0) { count = 2; }
- if (filter) {
- // 目前有滤镜的情况下不会合并绘制
- var data = this.drawData[this.drawDataLen] || {};
- data.type = 0 /* TEXTURE */;
- data.texture = texture;
- data.filter = filter;
- data.count = count;
- data.textureWidth = textureWidth;
- data.textureHeight = textureHeight;
- this.drawData[this.drawDataLen] = data;
- this.drawDataLen++;
- }
- else {
- if (this.drawDataLen == 0 || this.drawData[this.drawDataLen - 1].type != 0 /* TEXTURE */ || texture != this.drawData[this.drawDataLen - 1].texture || this.drawData[this.drawDataLen - 1].filter) {
- var data = this.drawData[this.drawDataLen] || {};
- data.type = 0 /* TEXTURE */;
- data.texture = texture;
- data.count = 0;
- this.drawData[this.drawDataLen] = data;
- this.drawDataLen++;
- }
- this.drawData[this.drawDataLen - 1].count += count;
- }
- };
- WebGLDrawCmdManager.prototype.pushChangeSmoothing = function (texture, smoothing) {
- texture["smoothing"] = smoothing;
- var data = this.drawData[this.drawDataLen] || {};
- data.type = 10 /* SMOOTHING */;
- data.texture = texture;
- data.smoothing = smoothing;
- this.drawData[this.drawDataLen] = data;
- this.drawDataLen++;
- };
- /**
- * 压入pushMask指令
- */
- WebGLDrawCmdManager.prototype.pushPushMask = function (count) {
- if (count === void 0) { count = 1; }
- var data = this.drawData[this.drawDataLen] || {};
- data.type = 2 /* PUSH_MASK */;
- data.count = count * 2;
- this.drawData[this.drawDataLen] = data;
- this.drawDataLen++;
- };
- /**
- * 压入popMask指令
- */
- WebGLDrawCmdManager.prototype.pushPopMask = function (count) {
- if (count === void 0) { count = 1; }
- var data = this.drawData[this.drawDataLen] || {};
- data.type = 3 /* POP_MASK */;
- data.count = count * 2;
- this.drawData[this.drawDataLen] = data;
- this.drawDataLen++;
- };
- /**
- * 压入混色指令
- */
- WebGLDrawCmdManager.prototype.pushSetBlend = function (value) {
- var len = this.drawDataLen;
- // 有无遍历到有效绘图操作
- var drawState = false;
- for (var i = len - 1; i >= 0; i--) {
- var data = this.drawData[i];
- if (data) {
- if (data.type == 0 /* TEXTURE */ || data.type == 1 /* RECT */) {
- drawState = true;
- }
- // 如果与上一次blend操作之间无有效绘图,上一次操作无效
- if (!drawState && data.type == 4 /* BLEND */) {
- this.drawData.splice(i, 1);
- this.drawDataLen--;
- continue;
- }
- // 如果与上一次blend操作重复,本次操作无效
- if (data.type == 4 /* BLEND */) {
- if (data.value == value) {
- return;
- }
- else {
- break;
- }
- }
- }
- }
- var _data = this.drawData[this.drawDataLen] || {};
- _data.type = 4 /* BLEND */;
- _data.value = value;
- this.drawData[this.drawDataLen] = _data;
- this.drawDataLen++;
- };
- /*
- * 压入resize render target命令
- */
- WebGLDrawCmdManager.prototype.pushResize = function (buffer, width, height) {
- var data = this.drawData[this.drawDataLen] || {};
- data.type = 5 /* RESIZE_TARGET */;
- data.buffer = buffer;
- data.width = width;
- data.height = height;
- this.drawData[this.drawDataLen] = data;
- this.drawDataLen++;
- };
- /*
- * 压入clear color命令
- */
- WebGLDrawCmdManager.prototype.pushClearColor = function () {
- var data = this.drawData[this.drawDataLen] || {};
- data.type = 6 /* CLEAR_COLOR */;
- this.drawData[this.drawDataLen] = data;
- this.drawDataLen++;
- };
- /**
- * 压入激活buffer命令
- */
- WebGLDrawCmdManager.prototype.pushActivateBuffer = function (buffer) {
- var len = this.drawDataLen;
- // 有无遍历到有效绘图操作
- var drawState = false;
- for (var i = len - 1; i >= 0; i--) {
- var data = this.drawData[i];
- if (data) {
- if (data.type != 4 /* BLEND */ && data.type != 7 /* ACT_BUFFER */) {
- drawState = true;
- }
- // 如果与上一次buffer操作之间无有效绘图,上一次操作无效
- if (!drawState && data.type == 7 /* ACT_BUFFER */) {
- this.drawData.splice(i, 1);
- this.drawDataLen--;
- continue;
- }
- // 如果与上一次buffer操作重复,本次操作无效
- // if(data.type == DRAWABLE_TYPE.ACT_BUFFER) {
- // if(data.buffer == buffer) {
- // return;
- // } else {
- // break;
- // }
- // }
- }
- }
- var _data = this.drawData[this.drawDataLen] || {};
- _data.type = 7 /* ACT_BUFFER */;
- _data.buffer = buffer;
- _data.width = buffer.rootRenderTarget.width;
- _data.height = buffer.rootRenderTarget.height;
- this.drawData[this.drawDataLen] = _data;
- this.drawDataLen++;
- };
- /*
- * 压入enabel scissor命令
- */
- WebGLDrawCmdManager.prototype.pushEnableScissor = function (x, y, width, height) {
- var data = this.drawData[this.drawDataLen] || {};
- data.type = 8 /* ENABLE_SCISSOR */;
- data.x = x;
- data.y = y;
- data.width = width;
- data.height = height;
- this.drawData[this.drawDataLen] = data;
- this.drawDataLen++;
- };
- /*
- * 压入disable scissor命令
- */
- WebGLDrawCmdManager.prototype.pushDisableScissor = function () {
- var data = this.drawData[this.drawDataLen] || {};
- data.type = 9 /* DISABLE_SCISSOR */;
- this.drawData[this.drawDataLen] = data;
- this.drawDataLen++;
- };
- /**
- * 清空命令数组
- */
- WebGLDrawCmdManager.prototype.clear = function () {
- for (var i = 0; i < this.drawDataLen; i++) {
- var data = this.drawData[i];
- data.type = 0;
- data.count = 0;
- data.texture = null;
- data.filter = null;
- data.uv = null;
- data.value = "";
- data.buffer = null;
- data.width = 0;
- data.height = 0;
- }
- this.drawDataLen = 0;
- };
- return WebGLDrawCmdManager;
- }());
- web.WebGLDrawCmdManager = WebGLDrawCmdManager;
- __reflect(WebGLDrawCmdManager.prototype, "egret.web.WebGLDrawCmdManager");
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- * 顶点数组管理对象
- * 用来维护顶点数组
- */
- var WebGLVertexArrayObject = (function () {
- function WebGLVertexArrayObject() {
- this.size = 2000;
- this.vertexMaxSize = this.size * 4;
- this.indicesMaxSize = this.size * 6;
- this.vertSize = 5;
- this.vertices = null;
- this.indices = null;
- this.indicesForMesh = null;
- this.vertexIndex = 0;
- this.indexIndex = 0;
- this.hasMesh = false;
- var numVerts = this.vertexMaxSize * this.vertSize;
- var numIndices = this.indicesMaxSize;
- this.vertices = new Float32Array(numVerts);
- this.indices = new Uint16Array(numIndices);
- this.indicesForMesh = new Uint16Array(numIndices);
- for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
- this.indices[i + 0] = j + 0;
- this.indices[i + 1] = j + 1;
- this.indices[i + 2] = j + 2;
- this.indices[i + 3] = j + 0;
- this.indices[i + 4] = j + 2;
- this.indices[i + 5] = j + 3;
- }
- }
- /**
- * 是否达到最大缓存数量
- */
- WebGLVertexArrayObject.prototype.reachMaxSize = function (vertexCount, indexCount) {
- if (vertexCount === void 0) { vertexCount = 4; }
- if (indexCount === void 0) { indexCount = 6; }
- return this.vertexIndex > this.vertexMaxSize - vertexCount || this.indexIndex > this.indicesMaxSize - indexCount;
- };
- /**
- * 获取缓存完成的顶点数组
- */
- WebGLVertexArrayObject.prototype.getVertices = function () {
- var view = this.vertices.subarray(0, this.vertexIndex * this.vertSize);
- return view;
- };
- /**
- * 获取缓存完成的索引数组
- */
- WebGLVertexArrayObject.prototype.getIndices = function () {
- return this.indices;
- };
- /**
- * 获取缓存完成的mesh索引数组
- */
- WebGLVertexArrayObject.prototype.getMeshIndices = function () {
- return this.indicesForMesh;
- };
- /**
- * 切换成mesh索引缓存方式
- */
- WebGLVertexArrayObject.prototype.changeToMeshIndices = function () {
- if (!this.hasMesh) {
- // 拷贝默认index信息到for mesh中
- for (var i = 0, l = this.indexIndex; i < l; ++i) {
- this.indicesForMesh[i] = this.indices[i];
- }
- this.hasMesh = true;
- }
- };
- WebGLVertexArrayObject.prototype.isMesh = function () {
- return this.hasMesh;
- };
- /**
- * 默认构成矩形
- */
- // private defaultMeshVertices = [0, 0, 1, 0, 1, 1, 0, 1];
- // private defaultMeshUvs = [
- // 0, 0,
- // 1, 0,
- // 1, 1,
- // 0, 1
- // ];
- // private defaultMeshIndices = [0, 1, 2, 0, 2, 3];
- /**
- * 缓存一组顶点
- */
- WebGLVertexArrayObject.prototype.cacheArrays = function (buffer, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, textureSourceWidth, textureSourceHeight, meshUVs, meshVertices, meshIndices, rotated) {
- var alpha = buffer.globalAlpha;
- //计算出绘制矩阵,之后把矩阵还原回之前的
- var locWorldTransform = buffer.globalMatrix;
- var a = locWorldTransform.a;
- var b = locWorldTransform.b;
- var c = locWorldTransform.c;
- var d = locWorldTransform.d;
- var tx = locWorldTransform.tx;
- var ty = locWorldTransform.ty;
- var offsetX = buffer.$offsetX;
- var offsetY = buffer.$offsetY;
- if (offsetX != 0 || offsetY != 0) {
- tx = offsetX * a + offsetY * c + tx;
- ty = offsetX * b + offsetY * d + ty;
- }
- if (!meshVertices) {
- if (destX != 0 || destY != 0) {
- tx = destX * a + destY * c + tx;
- ty = destX * b + destY * d + ty;
- }
- var a1 = destWidth / sourceWidth;
- if (a1 != 1) {
- a = a1 * a;
- b = a1 * b;
- }
- var d1 = destHeight / sourceHeight;
- if (d1 != 1) {
- c = d1 * c;
- d = d1 * d;
- }
- }
- if (meshVertices) {
- // 计算索引位置与赋值
- var vertices = this.vertices;
- var index = this.vertexIndex * this.vertSize;
- // 缓存顶点数组
- var i = 0, iD = 0, l = 0;
- var u = 0, v = 0, x = 0, y = 0;
- for (i = 0, l = meshUVs.length; i < l; i += 2) {
- iD = index + i * 5 / 2;
- x = meshVertices[i];
- y = meshVertices[i + 1];
- u = meshUVs[i];
- v = meshUVs[i + 1];
- // xy
- vertices[iD + 0] = a * x + c * y + tx;
- vertices[iD + 1] = b * x + d * y + ty;
- // uv
- if (rotated) {
- vertices[iD + 2] = (sourceX + (1.0 - v) * sourceHeight) / textureSourceWidth;
- vertices[iD + 3] = (sourceY + u * sourceWidth) / textureSourceHeight;
- }
- else {
- vertices[iD + 2] = (sourceX + u * sourceWidth) / textureSourceWidth;
- vertices[iD + 3] = (sourceY + v * sourceHeight) / textureSourceHeight;
- }
- // alpha
- vertices[iD + 4] = alpha;
- }
- // 缓存索引数组
- if (this.hasMesh) {
- for (var i_1 = 0, l_1 = meshIndices.length; i_1 < l_1; ++i_1) {
- this.indicesForMesh[this.indexIndex + i_1] = meshIndices[i_1] + this.vertexIndex;
- }
- }
- this.vertexIndex += meshUVs.length / 2;
- this.indexIndex += meshIndices.length;
- }
- else {
- var width = textureSourceWidth;
- var height = textureSourceHeight;
- var w = sourceWidth;
- var h = sourceHeight;
- sourceX = sourceX / width;
- sourceY = sourceY / height;
- var vertices = this.vertices;
- var index = this.vertexIndex * this.vertSize;
- if (rotated) {
- var temp = sourceWidth;
- sourceWidth = sourceHeight / width;
- sourceHeight = temp / height;
- // xy
- vertices[index++] = tx;
- vertices[index++] = ty;
- // uv
- vertices[index++] = sourceWidth + sourceX;
- vertices[index++] = sourceY;
- // alpha
- vertices[index++] = alpha;
- // xy
- vertices[index++] = a * w + tx;
- vertices[index++] = b * w + ty;
- // uv
- vertices[index++] = sourceWidth + sourceX;
- vertices[index++] = sourceHeight + sourceY;
- // alpha
- vertices[index++] = alpha;
- // xy
- vertices[index++] = a * w + c * h + tx;
- vertices[index++] = d * h + b * w + ty;
- // uv
- vertices[index++] = sourceX;
- vertices[index++] = sourceHeight + sourceY;
- // alpha
- vertices[index++] = alpha;
- // xy
- vertices[index++] = c * h + tx;
- vertices[index++] = d * h + ty;
- // uv
- vertices[index++] = sourceX;
- vertices[index++] = sourceY;
- // alpha
- vertices[index++] = alpha;
- }
- else {
- sourceWidth = sourceWidth / width;
- sourceHeight = sourceHeight / height;
- // xy
- vertices[index++] = tx;
- vertices[index++] = ty;
- // uv
- vertices[index++] = sourceX;
- vertices[index++] = sourceY;
- // alpha
- vertices[index++] = alpha;
- // xy
- vertices[index++] = a * w + tx;
- vertices[index++] = b * w + ty;
- // uv
- vertices[index++] = sourceWidth + sourceX;
- vertices[index++] = sourceY;
- // alpha
- vertices[index++] = alpha;
- // xy
- vertices[index++] = a * w + c * h + tx;
- vertices[index++] = d * h + b * w + ty;
- // uv
- vertices[index++] = sourceWidth + sourceX;
- vertices[index++] = sourceHeight + sourceY;
- // alpha
- vertices[index++] = alpha;
- // xy
- vertices[index++] = c * h + tx;
- vertices[index++] = d * h + ty;
- // uv
- vertices[index++] = sourceX;
- vertices[index++] = sourceHeight + sourceY;
- // alpha
- vertices[index++] = alpha;
- }
- // 缓存索引数组
- if (this.hasMesh) {
- var indicesForMesh = this.indicesForMesh;
- indicesForMesh[this.indexIndex + 0] = 0 + this.vertexIndex;
- indicesForMesh[this.indexIndex + 1] = 1 + this.vertexIndex;
- indicesForMesh[this.indexIndex + 2] = 2 + this.vertexIndex;
- indicesForMesh[this.indexIndex + 3] = 0 + this.vertexIndex;
- indicesForMesh[this.indexIndex + 4] = 2 + this.vertexIndex;
- indicesForMesh[this.indexIndex + 5] = 3 + this.vertexIndex;
- }
- this.vertexIndex += 4;
- this.indexIndex += 6;
- }
- };
- WebGLVertexArrayObject.prototype.clear = function () {
- this.hasMesh = false;
- this.vertexIndex = 0;
- this.indexIndex = 0;
- };
- return WebGLVertexArrayObject;
- }());
- web.WebGLVertexArrayObject = WebGLVertexArrayObject;
- __reflect(WebGLVertexArrayObject.prototype, "egret.web.WebGLVertexArrayObject");
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- * WebGLRenderTarget类
- * 一个WebGL渲染目标,拥有一个frame buffer和texture
- */
- var WebGLRenderTarget = (function (_super) {
- __extends(WebGLRenderTarget, _super);
- function WebGLRenderTarget(gl, width, height) {
- var _this = _super.call(this) || this;
- // 清除色
- _this.clearColor = [0, 0, 0, 0];
- // 是否启用frame buffer, 默认为true
- _this.useFrameBuffer = true;
- _this.gl = gl;
- // 如果尺寸为 0 chrome会报警
- _this.width = width || 1;
- _this.height = height || 1;
- return _this;
- }
- /**
- * 重置render target的尺寸
- */
- WebGLRenderTarget.prototype.resize = function (width, height) {
- var gl = this.gl;
- this.width = width;
- this.height = height;
- if (this.frameBuffer) {
- // 设置texture尺寸
- gl.bindTexture(gl.TEXTURE_2D, this.texture);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
- // gl.bindTexture(gl.TEXTURE_2D, null);
- }
- if (this.stencilBuffer) {
- gl.deleteRenderbuffer(this.stencilBuffer);
- this.stencilBuffer = null;
- }
- };
- /**
- * 激活此render target
- */
- WebGLRenderTarget.prototype.activate = function () {
- var gl = this.gl;
- gl.bindFramebuffer(gl.FRAMEBUFFER, this.getFrameBuffer());
- };
- /**
- * 获取frame buffer
- */
- WebGLRenderTarget.prototype.getFrameBuffer = function () {
- if (!this.useFrameBuffer) {
- return null;
- }
- return this.frameBuffer;
- };
- WebGLRenderTarget.prototype.initFrameBuffer = function () {
- if (!this.frameBuffer) {
- var gl = this.gl;
- // 创建材质
- this.texture = this.createTexture();
- // 创建frame buffer
- this.frameBuffer = gl.createFramebuffer();
- gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer);
- // 绑定材质
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);
- }
- };
- /**
- * 创建材质
- * TODO 创建材质的方法可以合并
- */
- WebGLRenderTarget.prototype.createTexture = function () {
- var gl = this.gl;
- var texture = gl.createTexture();
- texture["glContext"] = gl;
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- return texture;
- };
- /**
- * 清除render target颜色缓存
- */
- WebGLRenderTarget.prototype.clear = function (bind) {
- var gl = this.gl;
- if (bind) {
- this.activate();
- }
- gl.colorMask(true, true, true, true);
- gl.clearColor(this.clearColor[0], this.clearColor[1], this.clearColor[2], this.clearColor[3]);
- gl.clear(gl.COLOR_BUFFER_BIT);
- };
- WebGLRenderTarget.prototype.enabledStencil = function () {
- if (!this.frameBuffer || this.stencilBuffer) {
- return;
- }
- var gl = this.gl;
- // 设置render buffer的尺寸
- gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer); // 是否需要强制绑定?
- // 绑定stencil buffer
- this.stencilBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencilBuffer);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width, this.height);
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencilBuffer);
- // 此处不解绑是否会造成bug?
- // gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- };
- WebGLRenderTarget.prototype.dispose = function () {
- egret.WebGLUtils.deleteWebGLTexture(this.texture);
- };
- return WebGLRenderTarget;
- }(egret.HashObject));
- web.WebGLRenderTarget = WebGLRenderTarget;
- __reflect(WebGLRenderTarget.prototype, "egret.web.WebGLRenderTarget");
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * 创建一个canvas。
- */
- function createCanvas(width, height) {
- var canvas = document.createElement("canvas");
- if (!isNaN(width) && !isNaN(height)) {
- canvas.width = width;
- canvas.height = height;
- }
- return canvas;
- }
- /**
- * @private
- * WebGL上下文对象,提供简单的绘图接口
- * 抽象出此类,以实现共用一个context
- */
- var WebGLRenderContext = (function () {
- function WebGLRenderContext(width, height) {
- this.glID = null;
- this.projectionX = NaN;
- this.projectionY = NaN;
- this.contextLost = false;
- this.$scissorState = false;
- this.vertSize = 5;
- this.surface = createCanvas(width, height);
- if (egret.nativeRender) {
- return;
- }
- this.initWebGL();
- this.$bufferStack = [];
- var gl = this.context;
- this.vertexBuffer = gl.createBuffer();
- this.indexBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
- this.drawCmdManager = new web.WebGLDrawCmdManager();
- this.vao = new web.WebGLVertexArrayObject();
- this.setGlobalCompositeOperation("source-over");
- }
- WebGLRenderContext.getInstance = function (width, height) {
- if (this.instance) {
- return this.instance;
- }
- this.instance = new WebGLRenderContext(width, height);
- return this.instance;
- };
- /**
- * 推入一个RenderBuffer并绑定
- */
- WebGLRenderContext.prototype.pushBuffer = function (buffer) {
- this.$bufferStack.push(buffer);
- if (buffer != this.currentBuffer) {
- if (this.currentBuffer) {
- // this.$drawWebGL();
- }
- this.drawCmdManager.pushActivateBuffer(buffer);
- }
- this.currentBuffer = buffer;
- };
- /**
- * 推出一个RenderBuffer并绑定上一个RenderBuffer
- */
- WebGLRenderContext.prototype.popBuffer = function () {
- // 如果只剩下一个buffer,则不执行pop操作
- // 保证舞台buffer永远在最开始
- if (this.$bufferStack.length <= 1) {
- return;
- }
- var buffer = this.$bufferStack.pop();
- var lastBuffer = this.$bufferStack[this.$bufferStack.length - 1];
- // 重新绑定
- if (buffer != lastBuffer) {
- // this.$drawWebGL();
- this.drawCmdManager.pushActivateBuffer(lastBuffer);
- }
- this.currentBuffer = lastBuffer;
- };
- /**
- * 启用RenderBuffer
- */
- WebGLRenderContext.prototype.activateBuffer = function (buffer, width, height) {
- buffer.rootRenderTarget.activate();
- if (!this.bindIndices) {
- this.uploadIndicesArray(this.vao.getIndices());
- }
- buffer.restoreStencil();
- buffer.restoreScissor();
- this.onResize(width, height);
- };
- /**
- * 上传顶点数据
- */
- WebGLRenderContext.prototype.uploadVerticesArray = function (array) {
- var gl = this.context;
- gl.bufferData(gl.ARRAY_BUFFER, array, gl.STREAM_DRAW);
- // gl.bufferSubData(gl.ARRAY_BUFFER, 0, array);
- };
- /**
- * 上传索引数据
- */
- WebGLRenderContext.prototype.uploadIndicesArray = function (array) {
- var gl = this.context;
- gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array, gl.STATIC_DRAW);
- this.bindIndices = true;
- };
- /**
- * 销毁绘制对象
- */
- WebGLRenderContext.prototype.destroy = function () {
- this.surface.width = this.surface.height = 0;
- };
- WebGLRenderContext.prototype.onResize = function (width, height) {
- width = width || this.surface.width;
- height = height || this.surface.height;
- this.projectionX = width / 2;
- this.projectionY = -height / 2;
- if (this.context) {
- this.context.viewport(0, 0, width, height);
- }
- };
- /**
- * 改变渲染缓冲的大小并清空缓冲区
- * @param width 改变后的宽
- * @param height 改变后的高
- * @param useMaxSize 若传入true,则将改变后的尺寸与已有尺寸对比,保留较大的尺寸。
- */
- WebGLRenderContext.prototype.resize = function (width, height, useMaxSize) {
- var surface = this.surface;
- if (useMaxSize) {
- if (surface.width < width) {
- surface.width = width;
- }
- if (surface.height < height) {
- surface.height = height;
- }
- }
- else {
- if (surface.width != width) {
- surface.width = width;
- }
- if (surface.height != height) {
- surface.height = height;
- }
- }
- this.onResize();
- };
- WebGLRenderContext.prototype.initWebGL = function () {
- this.onResize();
- this.surface.addEventListener("webglcontextlost", this.handleContextLost.bind(this), false);
- this.surface.addEventListener("webglcontextrestored", this.handleContextRestored.bind(this), false);
- this.getWebGLContext();
- var gl = this.context;
- this.$maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
- };
- WebGLRenderContext.prototype.handleContextLost = function () {
- this.contextLost = true;
- };
- WebGLRenderContext.prototype.handleContextRestored = function () {
- this.initWebGL();
- this.contextLost = false;
- };
- WebGLRenderContext.prototype.getWebGLContext = function () {
- var options = {
- antialias: WebGLRenderContext.antialias,
- stencil: true //设置可以使用模板(用于不规则遮罩)
- };
- var gl;
- //todo 是否使用chrome源码names
- //let contextNames = ["moz-webgl", "webkit-3d", "experimental-webgl", "webgl", "3d"];
- var names = ["webgl", "experimental-webgl"];
- for (var i = 0; i < names.length; i++) {
- try {
- gl = this.surface.getContext(names[i], options);
- }
- catch (e) {
- }
- if (gl) {
- break;
- }
- }
- if (!gl) {
- egret.$error(1021);
- }
- this.setContext(gl);
- };
- WebGLRenderContext.prototype.setContext = function (gl) {
- this.context = gl;
- gl.id = WebGLRenderContext.glContextId++;
- this.glID = gl.id;
- gl.disable(gl.DEPTH_TEST);
- gl.disable(gl.CULL_FACE);
- gl.enable(gl.BLEND);
- gl.colorMask(true, true, true, true);
- // 目前只使用0号材质单元,默认开启
- gl.activeTexture(gl.TEXTURE0);
- };
- /**
- * 开启模版检测
- */
- WebGLRenderContext.prototype.enableStencilTest = function () {
- var gl = this.context;
- gl.enable(gl.STENCIL_TEST);
- };
- /**
- * 关闭模版检测
- */
- WebGLRenderContext.prototype.disableStencilTest = function () {
- var gl = this.context;
- gl.disable(gl.STENCIL_TEST);
- };
- /**
- * 开启scissor检测
- */
- WebGLRenderContext.prototype.enableScissorTest = function (rect) {
- var gl = this.context;
- gl.enable(gl.SCISSOR_TEST);
- gl.scissor(rect.x, rect.y, rect.width, rect.height);
- };
- /**
- * 关闭scissor检测
- */
- WebGLRenderContext.prototype.disableScissorTest = function () {
- var gl = this.context;
- gl.disable(gl.SCISSOR_TEST);
- };
- /**
- * 获取像素信息
- */
- WebGLRenderContext.prototype.getPixels = function (x, y, width, height, pixels) {
- var gl = this.context;
- gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
- };
- /**
- * 创建一个WebGLTexture
- */
- WebGLRenderContext.prototype.createTexture = function (bitmapData) {
- var gl = this.context;
- var texture = gl.createTexture();
- if (!texture) {
- //先创建texture失败,然后lost事件才发出来..
- this.contextLost = true;
- return;
- }
- texture.glContext = gl;
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmapData);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- return texture;
- };
- WebGLRenderContext.prototype.createTextureFromCompressedData = function (data, width, height, levels, internalFormat) {
- return null;
- };
- /**
- * 更新材质的bitmapData
- */
- WebGLRenderContext.prototype.updateTexture = function (texture, bitmapData) {
- var gl = this.context;
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmapData);
- };
- /**
- * 获取一个WebGLTexture
- * 如果有缓存的texture返回缓存的texture,如果没有则创建并缓存texture
- */
- WebGLRenderContext.prototype.getWebGLTexture = function (bitmapData) {
- if (!bitmapData.webGLTexture) {
- if (bitmapData.format == "image") {
- bitmapData.webGLTexture = this.createTexture(bitmapData.source);
- }
- else if (bitmapData.format == "pvr") {
- bitmapData.webGLTexture = this.createTextureFromCompressedData(bitmapData.source.pvrtcData, bitmapData.width, bitmapData.height, bitmapData.source.mipmapsCount, bitmapData.source.format);
- }
- if (bitmapData.$deleteSource && bitmapData.webGLTexture) {
- bitmapData.source = null;
- }
- if (bitmapData.webGLTexture) {
- //todo 默认值
- bitmapData.webGLTexture["smoothing"] = true;
- }
- }
- return bitmapData.webGLTexture;
- };
- /**
- * 清除矩形区域
- */
- WebGLRenderContext.prototype.clearRect = function (x, y, width, height) {
- if (x != 0 || y != 0 || width != this.surface.width || height != this.surface.height) {
- var buffer = this.currentBuffer;
- if (buffer.$hasScissor) {
- this.setGlobalCompositeOperation("destination-out");
- this.drawRect(x, y, width, height);
- this.setGlobalCompositeOperation("source-over");
- }
- else {
- var m = buffer.globalMatrix;
- if (m.b == 0 && m.c == 0) {
- x = x * m.a + m.tx;
- y = y * m.d + m.ty;
- width = width * m.a;
- height = height * m.d;
- this.enableScissor(x, -y - height + buffer.height, width, height);
- this.clear();
- this.disableScissor();
- }
- else {
- this.setGlobalCompositeOperation("destination-out");
- this.drawRect(x, y, width, height);
- this.setGlobalCompositeOperation("source-over");
- }
- }
- }
- else {
- this.clear();
- }
- };
- /**
- * 设置混色
- */
- WebGLRenderContext.prototype.setGlobalCompositeOperation = function (value) {
- this.drawCmdManager.pushSetBlend(value);
- };
- /**
- * 绘制图片,image参数可以是BitmapData或者renderTarget
- */
- WebGLRenderContext.prototype.drawImage = function (image, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, imageSourceWidth, imageSourceHeight, rotated, smoothing) {
- var buffer = this.currentBuffer;
- if (this.contextLost || !image || !buffer) {
- return;
- }
- var texture;
- var offsetX;
- var offsetY;
- if (image["texture"] || (image.source && image.source["texture"])) {
- // 如果是render target
- texture = image["texture"] || image.source["texture"];
- buffer.saveTransform();
- offsetX = buffer.$offsetX;
- offsetY = buffer.$offsetY;
- buffer.useOffset();
- buffer.transform(1, 0, 0, -1, 0, destHeight + destY * 2); // 翻转
- }
- else if (!image.source && !image.webGLTexture) {
- return;
- }
- else {
- texture = this.getWebGLTexture(image);
- }
- if (!texture) {
- return;
- }
- this.drawTexture(texture, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, imageSourceWidth, imageSourceHeight, undefined, undefined, undefined, undefined, rotated, smoothing);
- if (image.source && image.source["texture"]) {
- buffer.$offsetX = offsetX;
- buffer.$offsetY = offsetY;
- buffer.restoreTransform();
- }
- };
- /**
- * 绘制Mesh
- */
- WebGLRenderContext.prototype.drawMesh = function (image, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, imageSourceWidth, imageSourceHeight, meshUVs, meshVertices, meshIndices, bounds, rotated, smoothing) {
- var buffer = this.currentBuffer;
- if (this.contextLost || !image || !buffer) {
- return;
- }
- var texture;
- var offsetX;
- var offsetY;
- if (image["texture"] || (image.source && image.source["texture"])) {
- // 如果是render target
- texture = image["texture"] || image.source["texture"];
- buffer.saveTransform();
- offsetX = buffer.$offsetX;
- offsetY = buffer.$offsetY;
- buffer.useOffset();
- buffer.transform(1, 0, 0, -1, 0, destHeight + destY * 2); // 翻转
- }
- else if (!image.source && !image.webGLTexture) {
- return;
- }
- else {
- texture = this.getWebGLTexture(image);
- }
- if (!texture) {
- return;
- }
- this.drawTexture(texture, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, imageSourceWidth, imageSourceHeight, meshUVs, meshVertices, meshIndices, bounds, rotated, smoothing);
- if (image["texture"] || (image.source && image.source["texture"])) {
- buffer.$offsetX = offsetX;
- buffer.$offsetY = offsetY;
- buffer.restoreTransform();
- }
- };
- /**
- * 绘制材质
- */
- WebGLRenderContext.prototype.drawTexture = function (texture, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, textureWidth, textureHeight, meshUVs, meshVertices, meshIndices, bounds, rotated, smoothing) {
- var buffer = this.currentBuffer;
- if (this.contextLost || !texture || !buffer) {
- return;
- }
- if (meshVertices && meshIndices) {
- if (this.vao.reachMaxSize(meshVertices.length / 2, meshIndices.length)) {
- this.$drawWebGL();
- }
- }
- else {
- if (this.vao.reachMaxSize()) {
- this.$drawWebGL();
- }
- }
- if (smoothing != undefined && texture["smoothing"] != smoothing) {
- this.drawCmdManager.pushChangeSmoothing(texture, smoothing);
- }
- if (meshUVs) {
- this.vao.changeToMeshIndices();
- }
- var count = meshIndices ? meshIndices.length / 3 : 2;
- // 应用$filter,因为只可能是colorMatrixFilter,最后两个参数可不传
- this.drawCmdManager.pushDrawTexture(texture, count, this.$filter, textureWidth, textureHeight);
- this.vao.cacheArrays(buffer, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, textureWidth, textureHeight, meshUVs, meshVertices, meshIndices, rotated);
- };
- /**
- * 绘制矩形(仅用于遮罩擦除等)
- */
- WebGLRenderContext.prototype.drawRect = function (x, y, width, height) {
- var buffer = this.currentBuffer;
- if (this.contextLost || !buffer) {
- return;
- }
- if (this.vao.reachMaxSize()) {
- this.$drawWebGL();
- }
- this.drawCmdManager.pushDrawRect();
- this.vao.cacheArrays(buffer, 0, 0, width, height, x, y, width, height, width, height);
- };
- /**
- * 绘制遮罩
- */
- WebGLRenderContext.prototype.pushMask = function (x, y, width, height) {
- var buffer = this.currentBuffer;
- if (this.contextLost || !buffer) {
- return;
- }
- buffer.$stencilList.push({ x: x, y: y, width: width, height: height });
- if (this.vao.reachMaxSize()) {
- this.$drawWebGL();
- }
- this.drawCmdManager.pushPushMask();
- this.vao.cacheArrays(buffer, 0, 0, width, height, x, y, width, height, width, height);
- };
- /**
- * 恢复遮罩
- */
- WebGLRenderContext.prototype.popMask = function () {
- var buffer = this.currentBuffer;
- if (this.contextLost || !buffer) {
- return;
- }
- var mask = buffer.$stencilList.pop();
- if (this.vao.reachMaxSize()) {
- this.$drawWebGL();
- }
- this.drawCmdManager.pushPopMask();
- this.vao.cacheArrays(buffer, 0, 0, mask.width, mask.height, mask.x, mask.y, mask.width, mask.height, mask.width, mask.height);
- };
- /**
- * 清除颜色缓存
- */
- WebGLRenderContext.prototype.clear = function () {
- this.drawCmdManager.pushClearColor();
- };
- /**
- * 开启scissor test
- */
- WebGLRenderContext.prototype.enableScissor = function (x, y, width, height) {
- var buffer = this.currentBuffer;
- this.drawCmdManager.pushEnableScissor(x, y, width, height);
- buffer.$hasScissor = true;
- };
- /**
- * 关闭scissor test
- */
- WebGLRenderContext.prototype.disableScissor = function () {
- var buffer = this.currentBuffer;
- this.drawCmdManager.pushDisableScissor();
- buffer.$hasScissor = false;
- };
- WebGLRenderContext.prototype.$drawWebGL = function () {
- if (this.drawCmdManager.drawDataLen == 0 || this.contextLost) {
- return;
- }
- this.uploadVerticesArray(this.vao.getVertices());
- // 有mesh,则使用indicesForMesh
- if (this.vao.isMesh()) {
- this.uploadIndicesArray(this.vao.getMeshIndices());
- }
- var length = this.drawCmdManager.drawDataLen;
- var offset = 0;
- for (var i = 0; i < length; i++) {
- var data = this.drawCmdManager.drawData[i];
- offset = this.drawData(data, offset);
- // 计算draw call
- if (data.type == 7 /* ACT_BUFFER */) {
- this.activatedBuffer = data.buffer;
- }
- if (data.type == 0 /* TEXTURE */ || data.type == 1 /* RECT */ || data.type == 2 /* PUSH_MASK */ || data.type == 3 /* POP_MASK */) {
- if (this.activatedBuffer && this.activatedBuffer.$computeDrawCall) {
- this.activatedBuffer.$drawCalls++;
- }
- }
- }
- // 切换回默认indices
- if (this.vao.isMesh()) {
- this.uploadIndicesArray(this.vao.getIndices());
- }
- // 清空数据
- this.drawCmdManager.clear();
- this.vao.clear();
- };
- /**
- * 执行绘制命令
- */
- WebGLRenderContext.prototype.drawData = function (data, offset) {
- if (!data) {
- return;
- }
- var gl = this.context;
- var program;
- var filter = data.filter;
- switch (data.type) {
- case 0 /* TEXTURE */:
- if (filter) {
- if (filter.type === "custom") {
- program = web.EgretWebGLProgram.getProgram(gl, filter.$vertexSrc, filter.$fragmentSrc, filter.$shaderKey);
- }
- else if (filter.type === "colorTransform") {
- program = web.EgretWebGLProgram.getProgram(gl, web.EgretShaderLib.default_vert, web.EgretShaderLib.colorTransform_frag, "colorTransform");
- }
- else if (filter.type === "blurX") {
- program = web.EgretWebGLProgram.getProgram(gl, web.EgretShaderLib.default_vert, web.EgretShaderLib.blur_frag, "blur");
- }
- else if (filter.type === "blurY") {
- program = web.EgretWebGLProgram.getProgram(gl, web.EgretShaderLib.default_vert, web.EgretShaderLib.blur_frag, "blur");
- }
- else if (filter.type === "glow") {
- program = web.EgretWebGLProgram.getProgram(gl, web.EgretShaderLib.default_vert, web.EgretShaderLib.glow_frag, "glow");
- }
- }
- else {
- program = web.EgretWebGLProgram.getProgram(gl, web.EgretShaderLib.default_vert, web.EgretShaderLib.texture_frag, "texture");
- }
- this.activeProgram(gl, program);
- this.syncUniforms(program, filter, data.textureWidth, data.textureHeight);
- offset += this.drawTextureElements(data, offset);
- break;
- case 1 /* RECT */:
- program = web.EgretWebGLProgram.getProgram(gl, web.EgretShaderLib.default_vert, web.EgretShaderLib.primitive_frag, "primitive");
- this.activeProgram(gl, program);
- this.syncUniforms(program, filter, data.textureWidth, data.textureHeight);
- offset += this.drawRectElements(data, offset);
- break;
- case 2 /* PUSH_MASK */:
- program = web.EgretWebGLProgram.getProgram(gl, web.EgretShaderLib.default_vert, web.EgretShaderLib.primitive_frag, "primitive");
- this.activeProgram(gl, program);
- this.syncUniforms(program, filter, data.textureWidth, data.textureHeight);
- offset += this.drawPushMaskElements(data, offset);
- break;
- case 3 /* POP_MASK */:
- program = web.EgretWebGLProgram.getProgram(gl, web.EgretShaderLib.default_vert, web.EgretShaderLib.primitive_frag, "primitive");
- this.activeProgram(gl, program);
- this.syncUniforms(program, filter, data.textureWidth, data.textureHeight);
- offset += this.drawPopMaskElements(data, offset);
- break;
- case 4 /* BLEND */:
- this.setBlendMode(data.value);
- break;
- case 5 /* RESIZE_TARGET */:
- data.buffer.rootRenderTarget.resize(data.width, data.height);
- this.onResize(data.width, data.height);
- break;
- case 6 /* CLEAR_COLOR */:
- if (this.activatedBuffer) {
- var target = this.activatedBuffer.rootRenderTarget;
- if (target.width != 0 || target.height != 0) {
- target.clear(true);
- }
- }
- break;
- case 7 /* ACT_BUFFER */:
- this.activateBuffer(data.buffer, data.width, data.height);
- break;
- case 8 /* ENABLE_SCISSOR */:
- var buffer = this.activatedBuffer;
- if (buffer) {
- if (buffer.rootRenderTarget) {
- buffer.rootRenderTarget.enabledStencil();
- }
- buffer.enableScissor(data.x, data.y, data.width, data.height);
- }
- break;
- case 9 /* DISABLE_SCISSOR */:
- buffer = this.activatedBuffer;
- if (buffer) {
- buffer.disableScissor();
- }
- break;
- case 10 /* SMOOTHING */:
- gl.bindTexture(gl.TEXTURE_2D, data.texture);
- if (data.smoothing) {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- }
- else {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- }
- break;
- default:
- break;
- }
- return offset;
- };
- WebGLRenderContext.prototype.activeProgram = function (gl, program) {
- if (program != this.currentProgram) {
- gl.useProgram(program.id);
- // 目前所有attribute buffer的绑定方法都是一致的
- var attribute = program.attributes;
- for (var key in attribute) {
- if (key === "aVertexPosition") {
- gl.vertexAttribPointer(attribute["aVertexPosition"].location, 2, gl.FLOAT, false, 5 * 4, 0);
- gl.enableVertexAttribArray(attribute["aVertexPosition"].location);
- }
- else if (key === "aTextureCoord") {
- gl.vertexAttribPointer(attribute["aTextureCoord"].location, 2, gl.FLOAT, false, 5 * 4, 2 * 4);
- gl.enableVertexAttribArray(attribute["aTextureCoord"].location);
- }
- else if (key === "aColor") {
- gl.vertexAttribPointer(attribute["aColor"].location, 1, gl.FLOAT, false, 5 * 4, 4 * 4);
- gl.enableVertexAttribArray(attribute["aColor"].location);
- }
- }
- this.currentProgram = program;
- }
- };
- WebGLRenderContext.prototype.syncUniforms = function (program, filter, textureWidth, textureHeight) {
- var uniforms = program.uniforms;
- var isCustomFilter = filter && filter.type === "custom";
- for (var key in uniforms) {
- if (key === "projectionVector") {
- uniforms[key].setValue({ x: this.projectionX, y: this.projectionY });
- }
- else if (key === "uTextureSize") {
- uniforms[key].setValue({ x: textureWidth, y: textureHeight });
- }
- else if (key === "uSampler") {
- }
- else {
- var value = filter.$uniforms[key];
- if (value !== undefined) {
- uniforms[key].setValue(value);
- }
- else {
- // egret.warn("filter custom: uniform " + key + " not defined!");
- }
- }
- }
- };
- /**
- * 画texture
- **/
- WebGLRenderContext.prototype.drawTextureElements = function (data, offset) {
- var gl = this.context;
- gl.bindTexture(gl.TEXTURE_2D, data.texture);
- var size = data.count * 3;
- gl.drawElements(gl.TRIANGLES, size, gl.UNSIGNED_SHORT, offset * 2);
- return size;
- };
- /**
- * @private
- * 画rect
- **/
- WebGLRenderContext.prototype.drawRectElements = function (data, offset) {
- var gl = this.context;
- // gl.bindTexture(gl.TEXTURE_2D, null);
- var size = data.count * 3;
- gl.drawElements(gl.TRIANGLES, size, gl.UNSIGNED_SHORT, offset * 2);
- return size;
- };
- /**
- * 画push mask
- **/
- WebGLRenderContext.prototype.drawPushMaskElements = function (data, offset) {
- var gl = this.context;
- var size = data.count * 3;
- var buffer = this.activatedBuffer;
- if (buffer) {
- if (buffer.rootRenderTarget) {
- buffer.rootRenderTarget.enabledStencil();
- }
- if (buffer.stencilHandleCount == 0) {
- buffer.enableStencil();
- gl.clear(gl.STENCIL_BUFFER_BIT); // clear
- }
- var level = buffer.stencilHandleCount;
- buffer.stencilHandleCount++;
- gl.colorMask(false, false, false, false);
- gl.stencilFunc(gl.EQUAL, level, 0xFF);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
- // gl.bindTexture(gl.TEXTURE_2D, null);
- gl.drawElements(gl.TRIANGLES, size, gl.UNSIGNED_SHORT, offset * 2);
- gl.stencilFunc(gl.EQUAL, level + 1, 0xFF);
- gl.colorMask(true, true, true, true);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
- }
- return size;
- };
- /**
- * 画pop mask
- **/
- WebGLRenderContext.prototype.drawPopMaskElements = function (data, offset) {
- var gl = this.context;
- var size = data.count * 3;
- var buffer = this.activatedBuffer;
- if (buffer) {
- buffer.stencilHandleCount--;
- if (buffer.stencilHandleCount == 0) {
- buffer.disableStencil(); // skip this draw
- }
- else {
- var level = buffer.stencilHandleCount;
- gl.colorMask(false, false, false, false);
- gl.stencilFunc(gl.EQUAL, level + 1, 0xFF);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR);
- // gl.bindTexture(gl.TEXTURE_2D, null);
- gl.drawElements(gl.TRIANGLES, size, gl.UNSIGNED_SHORT, offset * 2);
- gl.stencilFunc(gl.EQUAL, level, 0xFF);
- gl.colorMask(true, true, true, true);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
- }
- }
- return size;
- };
- /**
- * 设置混色
- */
- WebGLRenderContext.prototype.setBlendMode = function (value) {
- var gl = this.context;
- var blendModeWebGL = WebGLRenderContext.blendModesForGL[value];
- if (blendModeWebGL) {
- gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
- }
- };
- /**
- * 应用滤镜绘制给定的render target
- * 此方法不会导致input被释放,所以如果需要释放input,需要调用此方法后手动调用release
- */
- WebGLRenderContext.prototype.drawTargetWidthFilters = function (filters, input) {
- var originInput = input, filtersLen = filters.length, output;
- // 应用前面的滤镜
- if (filtersLen > 1) {
- for (var i = 0; i < filtersLen - 1; i++) {
- var filter_1 = filters[i];
- var width = input.rootRenderTarget.width;
- var height = input.rootRenderTarget.height;
- output = web.WebGLRenderBuffer.create(width, height);
- output.setTransform(1, 0, 0, 1, 0, 0);
- output.globalAlpha = 1;
- this.drawToRenderTarget(filter_1, input, output);
- if (input != originInput) {
- web.WebGLRenderBuffer.release(input);
- }
- input = output;
- }
- }
- // 应用最后一个滤镜并绘制到当前场景中
- var filter = filters[filtersLen - 1];
- this.drawToRenderTarget(filter, input, this.currentBuffer);
- // 释放掉用于交换的buffer
- if (input != originInput) {
- web.WebGLRenderBuffer.release(input);
- }
- };
- /**
- * 向一个renderTarget中绘制
- * */
- WebGLRenderContext.prototype.drawToRenderTarget = function (filter, input, output) {
- if (this.contextLost) {
- return;
- }
- if (this.vao.reachMaxSize()) {
- this.$drawWebGL();
- }
- this.pushBuffer(output);
- var originInput = input, temp, width = input.rootRenderTarget.width, height = input.rootRenderTarget.height;
- // 模糊滤镜分别处理blurX与blurY
- if (filter.type == "blur") {
- var blurXFilter = filter.blurXFilter;
- var blurYFilter = filter.blurYFilter;
- if (blurXFilter.blurX != 0 && blurYFilter.blurY != 0) {
- temp = web.WebGLRenderBuffer.create(width, height);
- temp.setTransform(1, 0, 0, 1, 0, 0);
- temp.globalAlpha = 1;
- this.drawToRenderTarget(filter.blurXFilter, input, temp);
- if (input != originInput) {
- web.WebGLRenderBuffer.release(input);
- }
- input = temp;
- filter = blurYFilter;
- }
- else {
- filter = blurXFilter.blurX === 0 ? blurYFilter : blurXFilter;
- }
- }
- // 绘制input结果到舞台
- output.saveTransform();
- output.transform(1, 0, 0, -1, 0, height);
- this.vao.cacheArrays(output, 0, 0, width, height, 0, 0, width, height, width, height);
- output.restoreTransform();
- this.drawCmdManager.pushDrawTexture(input.rootRenderTarget.texture, 2, filter, width, height);
- // 释放掉input
- if (input != originInput) {
- web.WebGLRenderBuffer.release(input);
- }
- this.popBuffer();
- };
- WebGLRenderContext.initBlendMode = function () {
- WebGLRenderContext.blendModesForGL = {};
- WebGLRenderContext.blendModesForGL["source-over"] = [1, 771];
- WebGLRenderContext.blendModesForGL["lighter"] = [1, 1];
- WebGLRenderContext.blendModesForGL["lighter-in"] = [770, 771];
- WebGLRenderContext.blendModesForGL["destination-out"] = [0, 771];
- WebGLRenderContext.blendModesForGL["destination-in"] = [0, 770];
- };
- WebGLRenderContext.glContextId = 0;
- WebGLRenderContext.blendModesForGL = null;
- return WebGLRenderContext;
- }());
- web.WebGLRenderContext = WebGLRenderContext;
- __reflect(WebGLRenderContext.prototype, "egret.web.WebGLRenderContext");
- WebGLRenderContext.initBlendMode();
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- * WebGL渲染缓存
- */
- var WebGLRenderBuffer = (function (_super) {
- __extends(WebGLRenderBuffer, _super);
- function WebGLRenderBuffer(width, height, root) {
- var _this = _super.call(this) || this;
- _this.globalAlpha = 1;
- /**
- * stencil state
- * 模版开关状态
- */
- _this.stencilState = false;
- _this.$stencilList = [];
- _this.stencilHandleCount = 0;
- /**
- * scissor state
- * scissor 开关状态
- */
- _this.$scissorState = false;
- _this.scissorRect = new egret.Rectangle();
- _this.$hasScissor = false;
- _this.$drawCalls = 0;
- _this.$computeDrawCall = false;
- _this.globalMatrix = new egret.Matrix();
- _this.savedGlobalMatrix = new egret.Matrix();
- _this.$offsetX = 0;
- _this.$offsetY = 0;
- // 获取webglRenderContext
- _this.context = web.WebGLRenderContext.getInstance(width, height);
- if (egret.nativeRender) {
- if (root) {
- _this.surface = _this.context.surface;
- }
- else {
- _this.surface = new egret_native.NativeRenderSurface(_this, width, height, root);
- }
- _this.rootRenderTarget = null;
- return _this;
- }
- // buffer 对应的 render target
- _this.rootRenderTarget = new web.WebGLRenderTarget(_this.context.context, 3, 3);
- if (width && height) {
- _this.resize(width, height);
- }
- // 如果是第一个加入的buffer,说明是舞台buffer
- _this.root = root;
- // 如果是用于舞台渲染的renderBuffer,则默认添加renderTarget到renderContext中,而且是第一个
- if (_this.root) {
- _this.context.pushBuffer(_this);
- // 画布
- _this.surface = _this.context.surface;
- _this.$computeDrawCall = true;
- }
- else {
- // 由于创建renderTarget造成的frameBuffer绑定,这里重置绑定
- var lastBuffer = _this.context.activatedBuffer;
- if (lastBuffer) {
- lastBuffer.rootRenderTarget.activate();
- }
- _this.rootRenderTarget.initFrameBuffer();
- _this.surface = _this.rootRenderTarget;
- }
- return _this;
- }
- WebGLRenderBuffer.prototype.enableStencil = function () {
- if (!this.stencilState) {
- this.context.enableStencilTest();
- this.stencilState = true;
- }
- };
- WebGLRenderBuffer.prototype.disableStencil = function () {
- if (this.stencilState) {
- this.context.disableStencilTest();
- this.stencilState = false;
- }
- };
- WebGLRenderBuffer.prototype.restoreStencil = function () {
- if (this.stencilState) {
- this.context.enableStencilTest();
- }
- else {
- this.context.disableStencilTest();
- }
- };
- WebGLRenderBuffer.prototype.enableScissor = function (x, y, width, height) {
- if (!this.$scissorState) {
- this.$scissorState = true;
- this.scissorRect.setTo(x, y, width, height);
- this.context.enableScissorTest(this.scissorRect);
- }
- };
- WebGLRenderBuffer.prototype.disableScissor = function () {
- if (this.$scissorState) {
- this.$scissorState = false;
- this.scissorRect.setEmpty();
- this.context.disableScissorTest();
- }
- };
- WebGLRenderBuffer.prototype.restoreScissor = function () {
- if (this.$scissorState) {
- this.context.enableScissorTest(this.scissorRect);
- }
- else {
- this.context.disableScissorTest();
- }
- };
- Object.defineProperty(WebGLRenderBuffer.prototype, "width", {
- /**
- * 渲染缓冲的宽度,以像素为单位。
- * @readOnly
- */
- get: function () {
- if (egret.nativeRender) {
- return this.surface.width;
- }
- else {
- return this.rootRenderTarget.width;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WebGLRenderBuffer.prototype, "height", {
- /**
- * 渲染缓冲的高度,以像素为单位。
- * @readOnly
- */
- get: function () {
- if (egret.nativeRender) {
- return this.surface.height;
- }
- else {
- return this.rootRenderTarget.height;
- }
- },
- enumerable: true,
- configurable: true
- });
- /**
- * 改变渲染缓冲的大小并清空缓冲区
- * @param width 改变后的宽
- * @param height 改变后的高
- * @param useMaxSize 若传入true,则将改变后的尺寸与已有尺寸对比,保留较大的尺寸。
- */
- WebGLRenderBuffer.prototype.resize = function (width, height, useMaxSize) {
- width = width || 1;
- height = height || 1;
- if (egret.nativeRender) {
- this.surface.resize(width, height);
- return;
- }
- this.context.pushBuffer(this);
- // render target 尺寸重置
- if (width != this.rootRenderTarget.width || height != this.rootRenderTarget.height) {
- this.context.drawCmdManager.pushResize(this, width, height);
- // 同步更改宽高
- this.rootRenderTarget.width = width;
- this.rootRenderTarget.height = height;
- }
- // 如果是舞台的渲染缓冲,执行resize,否则surface大小不随之改变
- if (this.root) {
- this.context.resize(width, height, useMaxSize);
- }
- this.context.clear();
- this.context.popBuffer();
- };
- /**
- * 获取指定区域的像素
- */
- WebGLRenderBuffer.prototype.getPixels = function (x, y, width, height) {
- if (width === void 0) { width = 1; }
- if (height === void 0) { height = 1; }
- var pixels = new Uint8Array(4 * width * height);
- if (egret.nativeRender) {
- egret_native.activateBuffer(this);
- egret_native.nrGetPixels(x, y, width, height, pixels);
- egret_native.activateBuffer(null);
- }
- else {
- var useFrameBuffer = this.rootRenderTarget.useFrameBuffer;
- this.rootRenderTarget.useFrameBuffer = true;
- this.rootRenderTarget.activate();
- this.context.getPixels(x, y, width, height, pixels);
- this.rootRenderTarget.useFrameBuffer = useFrameBuffer;
- this.rootRenderTarget.activate();
- }
- //图像反转
- var result = new Uint8Array(4 * width * height);
- for (var i = 0; i < height; i++) {
- for (var j = 0; j < width; j++) {
- var index1 = (width * (height - i - 1) + j) * 4;
- var index2 = (width * i + j) * 4;
- var a = pixels[index2 + 3];
- result[index1] = Math.round(pixels[index2] / a * 255);
- result[index1 + 1] = Math.round(pixels[index2 + 1] / a * 255);
- result[index1 + 2] = Math.round(pixels[index2 + 2] / a * 255);
- result[index1 + 3] = pixels[index2 + 3];
- }
- }
- return result;
- };
- /**
- * 转换成base64字符串,如果图片(或者包含的图片)跨域,则返回null
- * @param type 转换的类型,如: "image/png","image/jpeg"
- */
- WebGLRenderBuffer.prototype.toDataURL = function (type, encoderOptions) {
- return this.context.surface.toDataURL(type, encoderOptions);
- };
- /**
- * 销毁绘制对象
- */
- WebGLRenderBuffer.prototype.destroy = function () {
- this.context.destroy();
- };
- WebGLRenderBuffer.prototype.onRenderFinish = function () {
- this.$drawCalls = 0;
- };
- /**
- * 交换frameBuffer中的图像到surface中
- * @param width 宽度
- * @param height 高度
- */
- WebGLRenderBuffer.prototype.drawFrameBufferToSurface = function (sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, clear) {
- if (clear === void 0) { clear = false; }
- this.rootRenderTarget.useFrameBuffer = false;
- this.rootRenderTarget.activate();
- this.context.disableStencilTest(); // 切换frameBuffer注意要禁用STENCIL_TEST
- this.context.disableScissorTest();
- this.setTransform(1, 0, 0, 1, 0, 0);
- this.globalAlpha = 1;
- this.context.setGlobalCompositeOperation("source-over");
- clear && this.context.clear();
- this.context.drawImage(this.rootRenderTarget, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, sourceWidth, sourceHeight, false);
- this.context.$drawWebGL();
- this.rootRenderTarget.useFrameBuffer = true;
- this.rootRenderTarget.activate();
- this.restoreStencil();
- this.restoreScissor();
- };
- /**
- * 交换surface的图像到frameBuffer中
- * @param width 宽度
- * @param height 高度
- */
- WebGLRenderBuffer.prototype.drawSurfaceToFrameBuffer = function (sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, clear) {
- if (clear === void 0) { clear = false; }
- this.rootRenderTarget.useFrameBuffer = true;
- this.rootRenderTarget.activate();
- this.context.disableStencilTest(); // 切换frameBuffer注意要禁用STENCIL_TEST
- this.context.disableScissorTest();
- this.setTransform(1, 0, 0, 1, 0, 0);
- this.globalAlpha = 1;
- this.context.setGlobalCompositeOperation("source-over");
- clear && this.context.clear();
- this.context.drawImage(this.context.surface, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight, sourceWidth, sourceHeight, false);
- this.context.$drawWebGL();
- this.rootRenderTarget.useFrameBuffer = false;
- this.rootRenderTarget.activate();
- this.restoreStencil();
- this.restoreScissor();
- };
- /**
- * 清空缓冲区数据
- */
- WebGLRenderBuffer.prototype.clear = function () {
- this.context.pushBuffer(this);
- this.context.clear();
- this.context.popBuffer();
- };
- WebGLRenderBuffer.prototype.setTransform = function (a, b, c, d, tx, ty) {
- // this.globalMatrix.setTo(a, b, c, d, tx, ty);
- var matrix = this.globalMatrix;
- matrix.a = a;
- matrix.b = b;
- matrix.c = c;
- matrix.d = d;
- matrix.tx = tx;
- matrix.ty = ty;
- };
- WebGLRenderBuffer.prototype.transform = function (a, b, c, d, tx, ty) {
- var matrix = this.globalMatrix;
- var a1 = matrix.a;
- var b1 = matrix.b;
- var c1 = matrix.c;
- var d1 = matrix.d;
- if (a != 1 || b != 0 || c != 0 || d != 1) {
- matrix.a = a * a1 + b * c1;
- matrix.b = a * b1 + b * d1;
- matrix.c = c * a1 + d * c1;
- matrix.d = c * b1 + d * d1;
- }
- matrix.tx = tx * a1 + ty * c1 + matrix.tx;
- matrix.ty = tx * b1 + ty * d1 + matrix.ty;
- };
- WebGLRenderBuffer.prototype.useOffset = function () {
- var self = this;
- if (self.$offsetX != 0 || self.$offsetY != 0) {
- self.globalMatrix.append(1, 0, 0, 1, self.$offsetX, self.$offsetY);
- self.$offsetX = self.$offsetY = 0;
- }
- };
- WebGLRenderBuffer.prototype.saveTransform = function () {
- var matrix = this.globalMatrix;
- var sMatrix = this.savedGlobalMatrix;
- sMatrix.a = matrix.a;
- sMatrix.b = matrix.b;
- sMatrix.c = matrix.c;
- sMatrix.d = matrix.d;
- sMatrix.tx = matrix.tx;
- sMatrix.ty = matrix.ty;
- };
- WebGLRenderBuffer.prototype.restoreTransform = function () {
- var matrix = this.globalMatrix;
- var sMatrix = this.savedGlobalMatrix;
- matrix.a = sMatrix.a;
- matrix.b = sMatrix.b;
- matrix.c = sMatrix.c;
- matrix.d = sMatrix.d;
- matrix.tx = sMatrix.tx;
- matrix.ty = sMatrix.ty;
- };
- /**
- * 创建一个buffer实例
- */
- WebGLRenderBuffer.create = function (width, height) {
- var buffer = renderBufferPool.pop();
- // width = Math.min(width, 1024);
- // height = Math.min(height, 1024);
- if (buffer) {
- buffer.resize(width, height);
- var matrix = buffer.globalMatrix;
- matrix.a = 1;
- matrix.b = 0;
- matrix.c = 0;
- matrix.d = 1;
- matrix.tx = 0;
- matrix.ty = 0;
- buffer.globalAlpha = 1;
- buffer.$offsetX = 0;
- buffer.$offsetY = 0;
- }
- else {
- buffer = new WebGLRenderBuffer(width, height);
- buffer.$computeDrawCall = false;
- }
- return buffer;
- };
- /**
- * 回收一个buffer实例
- */
- WebGLRenderBuffer.release = function (buffer) {
- renderBufferPool.push(buffer);
- };
- WebGLRenderBuffer.autoClear = true;
- return WebGLRenderBuffer;
- }(egret.HashObject));
- web.WebGLRenderBuffer = WebGLRenderBuffer;
- __reflect(WebGLRenderBuffer.prototype, "egret.web.WebGLRenderBuffer", ["egret.sys.RenderBuffer"]);
- var renderBufferPool = []; //渲染缓冲区对象池
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- var blendModes = ["source-over", "lighter", "destination-out"];
- var defaultCompositeOp = "source-over";
- var BLACK_COLOR = "#000000";
- var CAPS_STYLES = { none: 'butt', square: 'square', round: 'round' };
- var renderBufferPool = []; //渲染缓冲区对象池
- /**
- * @private
- * WebGL渲染器
- */
- var WebGLRenderer = (function () {
- function WebGLRenderer() {
- this.nestLevel = 0; //渲染的嵌套层次,0表示在调用堆栈的最外层。
- }
- /**
- * 渲染一个显示对象
- * @param displayObject 要渲染的显示对象
- * @param buffer 渲染缓冲
- * @param matrix 要对显示对象整体叠加的变换矩阵
- * @param dirtyList 脏矩形列表
- * @param forRenderTexture 绘制目标是RenderTexture的标志
- * @returns drawCall触发绘制的次数
- */
- WebGLRenderer.prototype.render = function (displayObject, buffer, matrix, forRenderTexture) {
- this.nestLevel++;
- var webglBuffer = buffer;
- var webglBufferContext = webglBuffer.context;
- var root = forRenderTexture ? displayObject : null;
- webglBufferContext.pushBuffer(webglBuffer);
- //绘制显示对象
- webglBuffer.transform(matrix.a, matrix.b, matrix.c, matrix.d, 0, 0);
- this.drawDisplayObject(displayObject, webglBuffer, matrix.tx, matrix.ty, true);
- webglBufferContext.$drawWebGL();
- var drawCall = webglBuffer.$drawCalls;
- webglBuffer.onRenderFinish();
- webglBufferContext.popBuffer();
- var invert = egret.Matrix.create();
- matrix.$invertInto(invert);
- webglBuffer.transform(invert.a, invert.b, invert.c, invert.d, 0, 0);
- egret.Matrix.release(invert);
- this.nestLevel--;
- if (this.nestLevel === 0) {
- //最大缓存6个渲染缓冲
- if (renderBufferPool.length > 6) {
- renderBufferPool.length = 6;
- }
- var length_3 = renderBufferPool.length;
- for (var i = 0; i < length_3; i++) {
- renderBufferPool[i].resize(0, 0);
- }
- }
- return drawCall;
- };
- /**
- * @private
- * 绘制一个显示对象
- */
- WebGLRenderer.prototype.drawDisplayObject = function (displayObject, buffer, offsetX, offsetY, isStage) {
- var drawCalls = 0;
- var node;
- var displayList = displayObject.$displayList;
- if (displayList && !isStage) {
- if (displayObject.$cacheDirty || displayObject.$renderDirty ||
- displayList.$canvasScaleX != egret.sys.DisplayList.$canvasScaleX ||
- displayList.$canvasScaleY != egret.sys.DisplayList.$canvasScaleY) {
- drawCalls += displayList.drawToSurface();
- }
- node = displayList.$renderNode;
- }
- else {
- if (displayObject.$renderDirty) {
- node = displayObject.$getRenderNode();
- }
- else {
- node = displayObject.$renderNode;
- }
- }
- displayObject.$cacheDirty = false;
- if (node) {
- drawCalls++;
- buffer.$offsetX = offsetX;
- buffer.$offsetY = offsetY;
- switch (node.type) {
- case 1 /* BitmapNode */:
- this.renderBitmap(node, buffer);
- break;
- case 2 /* TextNode */:
- this.renderText(node, buffer);
- break;
- case 3 /* GraphicsNode */:
- this.renderGraphics(node, buffer);
- break;
- case 4 /* GroupNode */:
- this.renderGroup(node, buffer);
- break;
- case 5 /* MeshNode */:
- this.renderMesh(node, buffer);
- break;
- case 6 /* NormalBitmapNode */:
- this.renderNormalBitmap(node, buffer);
- break;
- }
- buffer.$offsetX = 0;
- buffer.$offsetY = 0;
- }
- if (displayList && !isStage) {
- return drawCalls;
- }
- var children = displayObject.$children;
- if (children) {
- var length_4 = children.length;
- for (var i = 0; i < length_4; i++) {
- var child = children[i];
- var offsetX2 = void 0;
- var offsetY2 = void 0;
- var tempAlpha = void 0;
- if (child.$alpha != 1) {
- tempAlpha = buffer.globalAlpha;
- buffer.globalAlpha *= child.$alpha;
- }
- var savedMatrix = void 0;
- if (child.$useTranslate) {
- var m = child.$getMatrix();
- offsetX2 = offsetX + child.$x;
- offsetY2 = offsetY + child.$y;
- var m2 = buffer.globalMatrix;
- savedMatrix = egret.Matrix.create();
- savedMatrix.a = m2.a;
- savedMatrix.b = m2.b;
- savedMatrix.c = m2.c;
- savedMatrix.d = m2.d;
- savedMatrix.tx = m2.tx;
- savedMatrix.ty = m2.ty;
- buffer.transform(m.a, m.b, m.c, m.d, offsetX2, offsetY2);
- offsetX2 = -child.$anchorOffsetX;
- offsetY2 = -child.$anchorOffsetY;
- }
- else {
- offsetX2 = offsetX + child.$x - child.$anchorOffsetX;
- offsetY2 = offsetY + child.$y - child.$anchorOffsetY;
- }
- switch (child.$renderMode) {
- case 1 /* NONE */:
- break;
- case 2 /* FILTER */:
- drawCalls += this.drawWithFilter(child, buffer, offsetX2, offsetY2);
- break;
- case 3 /* CLIP */:
- drawCalls += this.drawWithClip(child, buffer, offsetX2, offsetY2);
- break;
- case 4 /* SCROLLRECT */:
- drawCalls += this.drawWithScrollRect(child, buffer, offsetX2, offsetY2);
- break;
- default:
- drawCalls += this.drawDisplayObject(child, buffer, offsetX2, offsetY2);
- break;
- }
- if (tempAlpha) {
- buffer.globalAlpha = tempAlpha;
- }
- if (savedMatrix) {
- var m = buffer.globalMatrix;
- m.a = savedMatrix.a;
- m.b = savedMatrix.b;
- m.c = savedMatrix.c;
- m.d = savedMatrix.d;
- m.tx = savedMatrix.tx;
- m.ty = savedMatrix.ty;
- egret.Matrix.release(savedMatrix);
- }
- }
- }
- return drawCalls;
- };
- /**
- * @private
- */
- WebGLRenderer.prototype.drawWithFilter = function (displayObject, buffer, offsetX, offsetY) {
- var drawCalls = 0;
- if (displayObject.$children && displayObject.$children.length == 0 && (!displayObject.$renderNode || displayObject.$renderNode.$getRenderCount() == 0)) {
- return drawCalls;
- }
- var filters = displayObject.$filters;
- var hasBlendMode = (displayObject.$blendMode !== 0);
- var compositeOp;
- if (hasBlendMode) {
- compositeOp = blendModes[displayObject.$blendMode];
- if (!compositeOp) {
- compositeOp = defaultCompositeOp;
- }
- }
- var displayBounds = displayObject.$getOriginalBounds();
- var displayBoundsX = displayBounds.x;
- var displayBoundsY = displayBounds.y;
- var displayBoundsWidth = displayBounds.width;
- var displayBoundsHeight = displayBounds.height;
- if (displayBoundsWidth <= 0 || displayBoundsHeight <= 0) {
- return drawCalls;
- }
- if (!displayObject.mask && filters.length == 1 && (filters[0].type == "colorTransform" || (filters[0].type === "custom" && filters[0].padding === 0))) {
- var childrenDrawCount = this.getRenderCount(displayObject);
- if (!displayObject.$children || childrenDrawCount == 1) {
- if (hasBlendMode) {
- buffer.context.setGlobalCompositeOperation(compositeOp);
- }
- buffer.context.$filter = filters[0];
- if (displayObject.$mask) {
- drawCalls += this.drawWithClip(displayObject, buffer, offsetX, offsetY);
- }
- else if (displayObject.$scrollRect || displayObject.$maskRect) {
- drawCalls += this.drawWithScrollRect(displayObject, buffer, offsetX, offsetY);
- }
- else {
- drawCalls += this.drawDisplayObject(displayObject, buffer, offsetX, offsetY);
- }
- buffer.context.$filter = null;
- if (hasBlendMode) {
- buffer.context.setGlobalCompositeOperation(defaultCompositeOp);
- }
- return drawCalls;
- }
- }
- // 为显示对象创建一个新的buffer
- var displayBuffer = this.createRenderBuffer(displayBoundsWidth, displayBoundsHeight);
- displayBuffer.context.pushBuffer(displayBuffer);
- //todo 可以优化减少draw次数
- if (displayObject.$mask) {
- drawCalls += this.drawWithClip(displayObject, displayBuffer, -displayBoundsX, -displayBoundsY);
- }
- else if (displayObject.$scrollRect || displayObject.$maskRect) {
- drawCalls += this.drawWithScrollRect(displayObject, displayBuffer, -displayBoundsX, -displayBoundsY);
- }
- else {
- drawCalls += this.drawDisplayObject(displayObject, displayBuffer, -displayBoundsX, -displayBoundsY);
- }
- displayBuffer.context.popBuffer();
- //绘制结果到屏幕
- if (drawCalls > 0) {
- if (hasBlendMode) {
- buffer.context.setGlobalCompositeOperation(compositeOp);
- }
- drawCalls++;
- // 绘制结果的时候,应用滤镜
- buffer.$offsetX = offsetX + displayBoundsX;
- buffer.$offsetY = offsetY + displayBoundsY;
- var savedMatrix = egret.Matrix.create();
- var curMatrix = buffer.globalMatrix;
- savedMatrix.a = curMatrix.a;
- savedMatrix.b = curMatrix.b;
- savedMatrix.c = curMatrix.c;
- savedMatrix.d = curMatrix.d;
- savedMatrix.tx = curMatrix.tx;
- savedMatrix.ty = curMatrix.ty;
- buffer.useOffset();
- buffer.context.drawTargetWidthFilters(filters, displayBuffer);
- curMatrix.a = savedMatrix.a;
- curMatrix.b = savedMatrix.b;
- curMatrix.c = savedMatrix.c;
- curMatrix.d = savedMatrix.d;
- curMatrix.tx = savedMatrix.tx;
- curMatrix.ty = savedMatrix.ty;
- egret.Matrix.release(savedMatrix);
- if (hasBlendMode) {
- buffer.context.setGlobalCompositeOperation(defaultCompositeOp);
- }
- }
- renderBufferPool.push(displayBuffer);
- return drawCalls;
- };
- WebGLRenderer.prototype.getRenderCount = function (displayObject) {
- var drawCount = 0;
- var node = displayObject.$getRenderNode();
- if (node) {
- drawCount += node.$getRenderCount();
- }
- if (displayObject.$children) {
- for (var _i = 0, _a = displayObject.$children; _i < _a.length; _i++) {
- var child = _a[_i];
- var filters = child.$filters;
- // 特殊处理有滤镜的对象
- if (filters && filters.length > 0) {
- return 2;
- }
- else if (child.$children) {
- drawCount += this.getRenderCount(child);
- }
- else {
- var node_1 = child.$getRenderNode();
- if (node_1) {
- drawCount += node_1.$getRenderCount();
- }
- }
- }
- }
- return drawCount;
- };
- /**
- * @private
- */
- WebGLRenderer.prototype.drawWithClip = function (displayObject, buffer, offsetX, offsetY) {
- var drawCalls = 0;
- var hasBlendMode = (displayObject.$blendMode !== 0);
- var compositeOp;
- if (hasBlendMode) {
- compositeOp = blendModes[displayObject.$blendMode];
- if (!compositeOp) {
- compositeOp = defaultCompositeOp;
- }
- }
- var scrollRect = displayObject.$scrollRect ? displayObject.$scrollRect : displayObject.$maskRect;
- var mask = displayObject.$mask;
- if (mask) {
- var maskRenderMatrix = mask.$getMatrix();
- //遮罩scaleX或scaleY为0,放弃绘制
- if ((maskRenderMatrix.a == 0 && maskRenderMatrix.b == 0) || (maskRenderMatrix.c == 0 && maskRenderMatrix.d == 0)) {
- return drawCalls;
- }
- }
- //没有遮罩,同时显示对象没有子项
- if (!mask && (!displayObject.$children || displayObject.$children.length == 0)) {
- if (scrollRect) {
- buffer.context.pushMask(scrollRect.x + offsetX, scrollRect.y + offsetY, scrollRect.width, scrollRect.height);
- }
- //绘制显示对象
- if (hasBlendMode) {
- buffer.context.setGlobalCompositeOperation(compositeOp);
- }
- drawCalls += this.drawDisplayObject(displayObject, buffer, offsetX, offsetY);
- if (hasBlendMode) {
- buffer.context.setGlobalCompositeOperation(defaultCompositeOp);
- }
- if (scrollRect) {
- buffer.context.popMask();
- }
- return drawCalls;
- }
- else {
- var displayBounds = displayObject.$getOriginalBounds();
- var displayBoundsX = displayBounds.x;
- var displayBoundsY = displayBounds.y;
- var displayBoundsWidth = displayBounds.width;
- var displayBoundsHeight = displayBounds.height;
- if (displayBoundsWidth <= 0 || displayBoundsHeight <= 0) {
- return drawCalls;
- }
- //绘制显示对象自身,若有scrollRect,应用clip
- var displayBuffer = this.createRenderBuffer(displayBoundsWidth, displayBoundsHeight);
- displayBuffer.context.pushBuffer(displayBuffer);
- drawCalls += this.drawDisplayObject(displayObject, displayBuffer, -displayBoundsX, -displayBoundsY);
- //绘制遮罩
- if (mask) {
- var maskBuffer = this.createRenderBuffer(displayBoundsWidth, displayBoundsHeight);
- maskBuffer.context.pushBuffer(maskBuffer);
- var maskMatrix = egret.Matrix.create();
- maskMatrix.copyFrom(mask.$getConcatenatedMatrix());
- mask.$getConcatenatedMatrixAt(displayObject, maskMatrix);
- maskMatrix.translate(-displayBoundsX, -displayBoundsY);
- maskBuffer.setTransform(maskMatrix.a, maskMatrix.b, maskMatrix.c, maskMatrix.d, maskMatrix.tx, maskMatrix.ty);
- egret.Matrix.release(maskMatrix);
- drawCalls += this.drawDisplayObject(mask, maskBuffer, 0, 0);
- maskBuffer.context.popBuffer();
- displayBuffer.context.setGlobalCompositeOperation("destination-in");
- displayBuffer.setTransform(1, 0, 0, -1, 0, maskBuffer.height);
- var maskBufferWidth = maskBuffer.rootRenderTarget.width;
- var maskBufferHeight = maskBuffer.rootRenderTarget.height;
- displayBuffer.context.drawTexture(maskBuffer.rootRenderTarget.texture, 0, 0, maskBufferWidth, maskBufferHeight, 0, 0, maskBufferWidth, maskBufferHeight, maskBufferWidth, maskBufferHeight);
- displayBuffer.setTransform(1, 0, 0, 1, 0, 0);
- displayBuffer.context.setGlobalCompositeOperation("source-over");
- maskBuffer.setTransform(1, 0, 0, 1, 0, 0);
- renderBufferPool.push(maskBuffer);
- }
- displayBuffer.context.setGlobalCompositeOperation(defaultCompositeOp);
- displayBuffer.context.popBuffer();
- //绘制结果到屏幕
- if (drawCalls > 0) {
- drawCalls++;
- if (hasBlendMode) {
- buffer.context.setGlobalCompositeOperation(compositeOp);
- }
- if (scrollRect) {
- buffer.context.pushMask(scrollRect.x + offsetX, scrollRect.y + offsetY, scrollRect.width, scrollRect.height);
- }
- var savedMatrix = egret.Matrix.create();
- var curMatrix = buffer.globalMatrix;
- savedMatrix.a = curMatrix.a;
- savedMatrix.b = curMatrix.b;
- savedMatrix.c = curMatrix.c;
- savedMatrix.d = curMatrix.d;
- savedMatrix.tx = curMatrix.tx;
- savedMatrix.ty = curMatrix.ty;
- curMatrix.append(1, 0, 0, -1, offsetX + displayBoundsX, offsetY + displayBoundsY + displayBuffer.height);
- var displayBufferWidth = displayBuffer.rootRenderTarget.width;
- var displayBufferHeight = displayBuffer.rootRenderTarget.height;
- buffer.context.drawTexture(displayBuffer.rootRenderTarget.texture, 0, 0, displayBufferWidth, displayBufferHeight, 0, 0, displayBufferWidth, displayBufferHeight, displayBufferWidth, displayBufferHeight);
- if (scrollRect) {
- displayBuffer.context.popMask();
- }
- if (hasBlendMode) {
- buffer.context.setGlobalCompositeOperation(defaultCompositeOp);
- }
- var matrix = buffer.globalMatrix;
- matrix.a = savedMatrix.a;
- matrix.b = savedMatrix.b;
- matrix.c = savedMatrix.c;
- matrix.d = savedMatrix.d;
- matrix.tx = savedMatrix.tx;
- matrix.ty = savedMatrix.ty;
- egret.Matrix.release(savedMatrix);
- }
- renderBufferPool.push(displayBuffer);
- return drawCalls;
- }
- };
- /**
- * @private
- */
- WebGLRenderer.prototype.drawWithScrollRect = function (displayObject, buffer, offsetX, offsetY) {
- var drawCalls = 0;
- var scrollRect = displayObject.$scrollRect ? displayObject.$scrollRect : displayObject.$maskRect;
- if (scrollRect.isEmpty()) {
- return drawCalls;
- }
- if (displayObject.$scrollRect) {
- offsetX -= scrollRect.x;
- offsetY -= scrollRect.y;
- }
- var m = buffer.globalMatrix;
- var context = buffer.context;
- var scissor = false;
- if (buffer.$hasScissor || m.b != 0 || m.c != 0) {
- buffer.context.pushMask(scrollRect.x + offsetX, scrollRect.y + offsetY, scrollRect.width, scrollRect.height);
- }
- else {
- var a = m.a;
- var d = m.d;
- var tx = m.tx;
- var ty = m.ty;
- var x = scrollRect.x + offsetX;
- var y = scrollRect.y + offsetY;
- var xMax = x + scrollRect.width;
- var yMax = y + scrollRect.height;
- var minX = void 0, minY = void 0, maxX = void 0, maxY = void 0;
- //优化,通常情况下不缩放的对象占多数,直接加上偏移量即可。
- if (a == 1.0 && d == 1.0) {
- minX = x + tx;
- minY = y + ty;
- maxX = xMax + tx;
- maxY = yMax + ty;
- }
- else {
- var x0 = a * x + tx;
- var y0 = d * y + ty;
- var x1 = a * xMax + tx;
- var y1 = d * y + ty;
- var x2 = a * xMax + tx;
- var y2 = d * yMax + ty;
- var x3 = a * x + tx;
- var y3 = d * yMax + ty;
- var tmp = 0;
- if (x0 > x1) {
- tmp = x0;
- x0 = x1;
- x1 = tmp;
- }
- if (x2 > x3) {
- tmp = x2;
- x2 = x3;
- x3 = tmp;
- }
- minX = (x0 < x2 ? x0 : x2);
- maxX = (x1 > x3 ? x1 : x3);
- if (y0 > y1) {
- tmp = y0;
- y0 = y1;
- y1 = tmp;
- }
- if (y2 > y3) {
- tmp = y2;
- y2 = y3;
- y3 = tmp;
- }
- minY = (y0 < y2 ? y0 : y2);
- maxY = (y1 > y3 ? y1 : y3);
- }
- context.enableScissor(minX, -maxY + buffer.height, maxX - minX, maxY - minY);
- scissor = true;
- }
- drawCalls += this.drawDisplayObject(displayObject, buffer, offsetX, offsetY);
- if (scissor) {
- context.disableScissor();
- }
- else {
- context.popMask();
- }
- return drawCalls;
- };
- /**
- * 将一个RenderNode对象绘制到渲染缓冲
- * @param node 要绘制的节点
- * @param buffer 渲染缓冲
- * @param matrix 要叠加的矩阵
- * @param forHitTest 绘制结果是用于碰撞检测。若为true,当渲染GraphicsNode时,会忽略透明度样式设置,全都绘制为不透明的。
- */
- WebGLRenderer.prototype.drawNodeToBuffer = function (node, buffer, matrix, forHitTest) {
- var webglBuffer = buffer;
- //pushRenderTARGET
- webglBuffer.context.pushBuffer(webglBuffer);
- webglBuffer.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty);
- this.renderNode(node, buffer, 0, 0, forHitTest);
- webglBuffer.context.$drawWebGL();
- webglBuffer.onRenderFinish();
- //popRenderTARGET
- webglBuffer.context.popBuffer();
- };
- /**
- * 将一个DisplayObject绘制到渲染缓冲,用于RenderTexture绘制
- * @param displayObject 要绘制的显示对象
- * @param buffer 渲染缓冲
- * @param matrix 要叠加的矩阵
- */
- WebGLRenderer.prototype.drawDisplayToBuffer = function (displayObject, buffer, matrix) {
- buffer.context.pushBuffer(buffer);
- if (matrix) {
- buffer.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty);
- }
- var node;
- if (displayObject.$renderDirty) {
- node = displayObject.$getRenderNode();
- }
- else {
- node = displayObject.$renderNode;
- }
- var drawCalls = 0;
- if (node) {
- drawCalls++;
- switch (node.type) {
- case 1 /* BitmapNode */:
- this.renderBitmap(node, buffer);
- break;
- case 2 /* TextNode */:
- this.renderText(node, buffer);
- break;
- case 3 /* GraphicsNode */:
- this.renderGraphics(node, buffer);
- break;
- case 4 /* GroupNode */:
- this.renderGroup(node, buffer);
- break;
- case 5 /* MeshNode */:
- this.renderMesh(node, buffer);
- break;
- case 6 /* NormalBitmapNode */:
- this.renderNormalBitmap(node, buffer);
- break;
- }
- }
- var children = displayObject.$children;
- if (children) {
- var length_5 = children.length;
- for (var i = 0; i < length_5; i++) {
- var child = children[i];
- switch (child.$renderMode) {
- case 1 /* NONE */:
- break;
- case 2 /* FILTER */:
- drawCalls += this.drawWithFilter(child, buffer, 0, 0);
- break;
- case 3 /* CLIP */:
- drawCalls += this.drawWithClip(child, buffer, 0, 0);
- break;
- case 4 /* SCROLLRECT */:
- drawCalls += this.drawWithScrollRect(child, buffer, 0, 0);
- break;
- default:
- drawCalls += this.drawDisplayObject(child, buffer, 0, 0);
- break;
- }
- }
- }
- buffer.context.$drawWebGL();
- buffer.onRenderFinish();
- buffer.context.popBuffer();
- return drawCalls;
- };
- /**
- * @private
- */
- WebGLRenderer.prototype.renderNode = function (node, buffer, offsetX, offsetY, forHitTest) {
- buffer.$offsetX = offsetX;
- buffer.$offsetY = offsetY;
- switch (node.type) {
- case 1 /* BitmapNode */:
- this.renderBitmap(node, buffer);
- break;
- case 2 /* TextNode */:
- this.renderText(node, buffer);
- break;
- case 3 /* GraphicsNode */:
- this.renderGraphics(node, buffer, forHitTest);
- break;
- case 4 /* GroupNode */:
- this.renderGroup(node, buffer);
- break;
- case 5 /* MeshNode */:
- this.renderMesh(node, buffer);
- break;
- case 6 /* NormalBitmapNode */:
- this.renderNormalBitmap(node, buffer);
- break;
- }
- };
- /**
- * @private
- */
- WebGLRenderer.prototype.renderNormalBitmap = function (node, buffer) {
- var image = node.image;
- if (!image) {
- return;
- }
- buffer.context.drawImage(image, node.sourceX, node.sourceY, node.sourceW, node.sourceH, node.drawX, node.drawY, node.drawW, node.drawH, node.imageWidth, node.imageHeight, node.rotated, node.smoothing);
- };
- /**
- * @private
- */
- WebGLRenderer.prototype.renderBitmap = function (node, buffer) {
- var image = node.image;
- if (!image) {
- return;
- }
- //buffer.imageSmoothingEnabled = node.smoothing;
- var data = node.drawData;
- var length = data.length;
- var pos = 0;
- var m = node.matrix;
- var blendMode = node.blendMode;
- var alpha = node.alpha;
- var savedMatrix;
- var offsetX;
- var offsetY;
- if (m) {
- savedMatrix = egret.Matrix.create();
- var curMatrix = buffer.globalMatrix;
- savedMatrix.a = curMatrix.a;
- savedMatrix.b = curMatrix.b;
- savedMatrix.c = curMatrix.c;
- savedMatrix.d = curMatrix.d;
- savedMatrix.tx = curMatrix.tx;
- savedMatrix.ty = curMatrix.ty;
- offsetX = buffer.$offsetX;
- offsetY = buffer.$offsetY;
- buffer.useOffset();
- buffer.transform(m.a, m.b, m.c, m.d, m.tx, m.ty);
- }
- //这里不考虑嵌套
- if (blendMode) {
- buffer.context.setGlobalCompositeOperation(blendModes[blendMode]);
- }
- var originAlpha;
- if (alpha == alpha) {
- originAlpha = buffer.globalAlpha;
- buffer.globalAlpha *= alpha;
- }
- if (node.filter) {
- buffer.context.$filter = node.filter;
- while (pos < length) {
- buffer.context.drawImage(image, data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], node.imageWidth, node.imageHeight, node.rotated, node.smoothing);
- }
- buffer.context.$filter = null;
- }
- else {
- while (pos < length) {
- buffer.context.drawImage(image, data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], node.imageWidth, node.imageHeight, node.rotated, node.smoothing);
- }
- }
- if (blendMode) {
- buffer.context.setGlobalCompositeOperation(defaultCompositeOp);
- }
- if (alpha == alpha) {
- buffer.globalAlpha = originAlpha;
- }
- if (m) {
- var matrix = buffer.globalMatrix;
- matrix.a = savedMatrix.a;
- matrix.b = savedMatrix.b;
- matrix.c = savedMatrix.c;
- matrix.d = savedMatrix.d;
- matrix.tx = savedMatrix.tx;
- matrix.ty = savedMatrix.ty;
- buffer.$offsetX = offsetX;
- buffer.$offsetY = offsetY;
- egret.Matrix.release(savedMatrix);
- }
- };
- /**
- * @private
- */
- WebGLRenderer.prototype.renderMesh = function (node, buffer) {
- var image = node.image;
- //buffer.imageSmoothingEnabled = node.smoothing;
- var data = node.drawData;
- var length = data.length;
- var pos = 0;
- var m = node.matrix;
- var blendMode = node.blendMode;
- var alpha = node.alpha;
- var savedMatrix;
- var offsetX;
- var offsetY;
- if (m) {
- savedMatrix = egret.Matrix.create();
- var curMatrix = buffer.globalMatrix;
- savedMatrix.a = curMatrix.a;
- savedMatrix.b = curMatrix.b;
- savedMatrix.c = curMatrix.c;
- savedMatrix.d = curMatrix.d;
- savedMatrix.tx = curMatrix.tx;
- savedMatrix.ty = curMatrix.ty;
- offsetX = buffer.$offsetX;
- offsetY = buffer.$offsetY;
- buffer.useOffset();
- buffer.transform(m.a, m.b, m.c, m.d, m.tx, m.ty);
- }
- //这里不考虑嵌套
- if (blendMode) {
- buffer.context.setGlobalCompositeOperation(blendModes[blendMode]);
- }
- var originAlpha;
- if (alpha == alpha) {
- originAlpha = buffer.globalAlpha;
- buffer.globalAlpha *= alpha;
- }
- if (node.filter) {
- buffer.context.$filter = node.filter;
- while (pos < length) {
- buffer.context.drawMesh(image, data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], node.imageWidth, node.imageHeight, node.uvs, node.vertices, node.indices, node.bounds, node.rotated, node.smoothing);
- }
- buffer.context.$filter = null;
- }
- else {
- while (pos < length) {
- buffer.context.drawMesh(image, data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], data[pos++], node.imageWidth, node.imageHeight, node.uvs, node.vertices, node.indices, node.bounds, node.rotated, node.smoothing);
- }
- }
- if (blendMode) {
- buffer.context.setGlobalCompositeOperation(defaultCompositeOp);
- }
- if (alpha == alpha) {
- buffer.globalAlpha = originAlpha;
- }
- if (m) {
- var matrix = buffer.globalMatrix;
- matrix.a = savedMatrix.a;
- matrix.b = savedMatrix.b;
- matrix.c = savedMatrix.c;
- matrix.d = savedMatrix.d;
- matrix.tx = savedMatrix.tx;
- matrix.ty = savedMatrix.ty;
- buffer.$offsetX = offsetX;
- buffer.$offsetY = offsetY;
- egret.Matrix.release(savedMatrix);
- }
- };
- /**
- * @private
- */
- WebGLRenderer.prototype.renderText = function (node, buffer) {
- var width = node.width - node.x;
- var height = node.height - node.y;
- if (width <= 0 || height <= 0 || !width || !height || node.drawData.length == 0) {
- return;
- }
- var canvasScaleX = egret.sys.DisplayList.$canvasScaleX;
- var canvasScaleY = egret.sys.DisplayList.$canvasScaleY;
- var maxTextureSize = buffer.context.$maxTextureSize;
- if (width * canvasScaleX > maxTextureSize) {
- canvasScaleX *= maxTextureSize / (width * canvasScaleX);
- }
- if (height * canvasScaleY > maxTextureSize) {
- canvasScaleY *= maxTextureSize / (height * canvasScaleY);
- }
- width *= canvasScaleX;
- height *= canvasScaleY;
- var x = node.x * canvasScaleX;
- var y = node.y * canvasScaleY;
- if (node.$canvasScaleX != canvasScaleX || node.$canvasScaleY != canvasScaleY) {
- node.$canvasScaleX = canvasScaleX;
- node.$canvasScaleY = canvasScaleY;
- node.dirtyRender = true;
- }
- if (!this.canvasRenderBuffer || !this.canvasRenderBuffer.context) {
- this.canvasRenderer = new egret.CanvasRenderer();
- this.canvasRenderBuffer = new web.CanvasRenderBuffer(width, height);
- }
- else if (node.dirtyRender) {
- this.canvasRenderBuffer.resize(width, height);
- }
- if (!this.canvasRenderBuffer.context) {
- return;
- }
- if (canvasScaleX != 1 || canvasScaleY != 1) {
- this.canvasRenderBuffer.context.setTransform(canvasScaleX, 0, 0, canvasScaleY, 0, 0);
- }
- if (x || y) {
- if (node.dirtyRender) {
- this.canvasRenderBuffer.context.setTransform(canvasScaleX, 0, 0, canvasScaleY, -x, -y);
- }
- buffer.transform(1, 0, 0, 1, x / canvasScaleX, y / canvasScaleY);
- }
- else if (canvasScaleX != 1 || canvasScaleY != 1) {
- this.canvasRenderBuffer.context.setTransform(canvasScaleX, 0, 0, canvasScaleY, 0, 0);
- }
- if (node.dirtyRender) {
- var surface = this.canvasRenderBuffer.surface;
- this.canvasRenderer.renderText(node, this.canvasRenderBuffer.context);
- // 拷贝canvas到texture
- var texture = node.$texture;
- if (!texture) {
- texture = buffer.context.createTexture(surface);
- node.$texture = texture;
- }
- else {
- // 重新拷贝新的图像
- buffer.context.updateTexture(texture, surface);
- }
- // 保存材质尺寸
- node.$textureWidth = surface.width;
- node.$textureHeight = surface.height;
- }
- var textureWidth = node.$textureWidth;
- var textureHeight = node.$textureHeight;
- buffer.context.drawTexture(node.$texture, 0, 0, textureWidth, textureHeight, 0, 0, textureWidth / canvasScaleX, textureHeight / canvasScaleY, textureWidth, textureHeight);
- if (x || y) {
- if (node.dirtyRender) {
- this.canvasRenderBuffer.context.setTransform(canvasScaleX, 0, 0, canvasScaleY, 0, 0);
- }
- buffer.transform(1, 0, 0, 1, -x / canvasScaleX, -y / canvasScaleY);
- }
- node.dirtyRender = false;
- };
- /**
- * @private
- */
- WebGLRenderer.prototype.renderGraphics = function (node, buffer, forHitTest) {
- var width = node.width;
- var height = node.height;
- if (width <= 0 || height <= 0 || !width || !height || node.drawData.length == 0) {
- return;
- }
- var canvasScaleX = egret.sys.DisplayList.$canvasScaleX;
- var canvasScaleY = egret.sys.DisplayList.$canvasScaleY;
- if (width * canvasScaleX < 1 || height * canvasScaleY < 1) {
- canvasScaleX = canvasScaleY = 1;
- }
- if (node.$canvasScaleX != canvasScaleX || node.$canvasScaleY != canvasScaleY) {
- node.$canvasScaleX = canvasScaleX;
- node.$canvasScaleY = canvasScaleY;
- node.dirtyRender = true;
- }
- //缩放叠加 width2 / width 填满整个区域
- width = width * canvasScaleX;
- height = height * canvasScaleY;
- var width2 = Math.ceil(width);
- var height2 = Math.ceil(height);
- canvasScaleX *= width2 / width;
- canvasScaleY *= height2 / height;
- width = width2;
- height = height2;
- if (!this.canvasRenderBuffer || !this.canvasRenderBuffer.context) {
- this.canvasRenderer = new egret.CanvasRenderer();
- this.canvasRenderBuffer = new web.CanvasRenderBuffer(width, height);
- }
- else if (node.dirtyRender || forHitTest) {
- this.canvasRenderBuffer.resize(width, height);
- }
- if (!this.canvasRenderBuffer.context) {
- return;
- }
- if (canvasScaleX != 1 || canvasScaleY != 1) {
- this.canvasRenderBuffer.context.setTransform(canvasScaleX, 0, 0, canvasScaleY, 0, 0);
- }
- if (node.x || node.y) {
- if (node.dirtyRender || forHitTest) {
- this.canvasRenderBuffer.context.translate(-node.x, -node.y);
- }
- buffer.transform(1, 0, 0, 1, node.x, node.y);
- }
- var surface = this.canvasRenderBuffer.surface;
- if (forHitTest) {
- this.canvasRenderer.renderGraphics(node, this.canvasRenderBuffer.context, true);
- egret.WebGLUtils.deleteWebGLTexture(surface);
- var texture = buffer.context.getWebGLTexture(surface);
- buffer.context.drawTexture(texture, 0, 0, width, height, 0, 0, width, height, surface.width, surface.height);
- }
- else {
- if (node.dirtyRender) {
- this.canvasRenderer.renderGraphics(node, this.canvasRenderBuffer.context);
- // 拷贝canvas到texture
- var texture = node.$texture;
- if (!texture) {
- texture = buffer.context.createTexture(surface);
- node.$texture = texture;
- }
- else {
- // 重新拷贝新的图像
- buffer.context.updateTexture(texture, surface);
- }
- // 保存材质尺寸
- node.$textureWidth = surface.width;
- node.$textureHeight = surface.height;
- }
- var textureWidth = node.$textureWidth;
- var textureHeight = node.$textureHeight;
- buffer.context.drawTexture(node.$texture, 0, 0, textureWidth, textureHeight, 0, 0, textureWidth / canvasScaleX, textureHeight / canvasScaleY, textureWidth, textureHeight);
- }
- if (node.x || node.y) {
- if (node.dirtyRender || forHitTest) {
- this.canvasRenderBuffer.context.translate(node.x, node.y);
- }
- buffer.transform(1, 0, 0, 1, -node.x, -node.y);
- }
- if (!forHitTest) {
- node.dirtyRender = false;
- }
- };
- WebGLRenderer.prototype.renderGroup = function (groupNode, buffer) {
- var m = groupNode.matrix;
- var savedMatrix;
- var offsetX;
- var offsetY;
- if (m) {
- savedMatrix = egret.Matrix.create();
- var curMatrix = buffer.globalMatrix;
- savedMatrix.a = curMatrix.a;
- savedMatrix.b = curMatrix.b;
- savedMatrix.c = curMatrix.c;
- savedMatrix.d = curMatrix.d;
- savedMatrix.tx = curMatrix.tx;
- savedMatrix.ty = curMatrix.ty;
- offsetX = buffer.$offsetX;
- offsetY = buffer.$offsetY;
- buffer.useOffset();
- buffer.transform(m.a, m.b, m.c, m.d, m.tx, m.ty);
- }
- var children = groupNode.drawData;
- var length = children.length;
- for (var i = 0; i < length; i++) {
- var node = children[i];
- this.renderNode(node, buffer, buffer.$offsetX, buffer.$offsetY);
- }
- if (m) {
- var matrix = buffer.globalMatrix;
- matrix.a = savedMatrix.a;
- matrix.b = savedMatrix.b;
- matrix.c = savedMatrix.c;
- matrix.d = savedMatrix.d;
- matrix.tx = savedMatrix.tx;
- matrix.ty = savedMatrix.ty;
- buffer.$offsetX = offsetX;
- buffer.$offsetY = offsetY;
- egret.Matrix.release(savedMatrix);
- }
- };
- /**
- * @private
- */
- WebGLRenderer.prototype.createRenderBuffer = function (width, height) {
- var buffer = renderBufferPool.pop();
- if (buffer) {
- buffer.resize(width, height);
- }
- else {
- buffer = new web.WebGLRenderBuffer(width, height);
- buffer.$computeDrawCall = false;
- }
- return buffer;
- };
- return WebGLRenderer;
- }());
- web.WebGLRenderer = WebGLRenderer;
- __reflect(WebGLRenderer.prototype, "egret.web.WebGLRenderer", ["egret.sys.SystemRenderer"]);
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var EgretWebGLAttribute = (function () {
- function EgretWebGLAttribute(gl, program, attributeData) {
- this.gl = gl;
- this.name = attributeData.name;
- this.type = attributeData.type;
- this.size = attributeData.size;
- this.location = gl.getAttribLocation(program, this.name);
- this.count = 0;
- this.initCount(gl);
- this.format = gl.FLOAT;
- this.initFormat(gl);
- }
- EgretWebGLAttribute.prototype.initCount = function (gl) {
- var type = this.type;
- switch (type) {
- case 5126 /* FLOAT */:
- case 5120 /* BYTE */:
- case 5121 /* UNSIGNED_BYTE */:
- case 5123 /* UNSIGNED_SHORT */:
- this.count = 1;
- break;
- case 35664 /* FLOAT_VEC2 */:
- this.count = 2;
- break;
- case 35665 /* FLOAT_VEC3 */:
- this.count = 3;
- break;
- case 35666 /* FLOAT_VEC4 */:
- this.count = 4;
- break;
- }
- };
- EgretWebGLAttribute.prototype.initFormat = function (gl) {
- var type = this.type;
- switch (type) {
- case 5126 /* FLOAT */:
- case 35664 /* FLOAT_VEC2 */:
- case 35665 /* FLOAT_VEC3 */:
- case 35666 /* FLOAT_VEC4 */:
- this.format = gl.FLOAT;
- break;
- case 5121 /* UNSIGNED_BYTE */:
- this.format = gl.UNSIGNED_BYTE;
- break;
- case 5123 /* UNSIGNED_SHORT */:
- this.format = gl.UNSIGNED_SHORT;
- break;
- case 5120 /* BYTE */:
- this.format = gl.BYTE;
- break;
- }
- };
- return EgretWebGLAttribute;
- }());
- web.EgretWebGLAttribute = EgretWebGLAttribute;
- __reflect(EgretWebGLAttribute.prototype, "egret.web.EgretWebGLAttribute");
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- function loadShader(gl, type, source) {
- var shader = gl.createShader(type);
- gl.shaderSource(shader, source);
- gl.compileShader(shader);
- var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
- if (!compiled) {
- console.log("shader not compiled!");
- console.log(gl.getShaderInfoLog(shader));
- }
- return shader;
- }
- function createWebGLProgram(gl, vertexShader, fragmentShader) {
- var program = gl.createProgram();
- gl.attachShader(program, vertexShader);
- gl.attachShader(program, fragmentShader);
- gl.linkProgram(program);
- return program;
- }
- function extractAttributes(gl, program) {
- var attributes = {};
- var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
- for (var i = 0; i < totalAttributes; i++) {
- var attribData = gl.getActiveAttrib(program, i);
- var name_2 = attribData.name;
- var attribute = new web.EgretWebGLAttribute(gl, program, attribData);
- attributes[name_2] = attribute;
- }
- return attributes;
- }
- function extractUniforms(gl, program) {
- var uniforms = {};
- var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
- for (var i = 0; i < totalUniforms; i++) {
- var uniformData = gl.getActiveUniform(program, i);
- var name_3 = uniformData.name;
- var uniform = new web.EgretWebGLUniform(gl, program, uniformData);
- uniforms[name_3] = uniform;
- }
- return uniforms;
- }
- /**
- * @private
- */
- var EgretWebGLProgram = (function () {
- function EgretWebGLProgram(gl, vertSource, fragSource) {
- this.vshaderSource = vertSource;
- this.fshaderSource = fragSource;
- this.vertexShader = loadShader(gl, gl.VERTEX_SHADER, this.vshaderSource);
- this.fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, this.fshaderSource);
- this.id = createWebGLProgram(gl, this.vertexShader, this.fragmentShader);
- this.uniforms = extractUniforms(gl, this.id);
- this.attributes = extractAttributes(gl, this.id);
- }
- /**
- * 获取所需的WebGL Program
- * @param key {string} 对于唯一的program程序,对应唯一的key
- */
- EgretWebGLProgram.getProgram = function (gl, vertSource, fragSource, key) {
- if (!this.programCache[key]) {
- this.programCache[key] = new EgretWebGLProgram(gl, vertSource, fragSource);
- }
- return this.programCache[key];
- };
- EgretWebGLProgram.deleteProgram = function (gl, vertSource, fragSource, key) {
- // TODO delete
- };
- EgretWebGLProgram.programCache = {};
- return EgretWebGLProgram;
- }());
- web.EgretWebGLProgram = EgretWebGLProgram;
- __reflect(EgretWebGLProgram.prototype, "egret.web.EgretWebGLProgram");
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- //////////////////////////////////////////////////////////////////////////////////////
- //
- // Copyright (c) 2014-present, Egret Technology.
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // * Neither the name of the Egret nor the
- // names of its contributors may be used to endorse or promote products
- // derived from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
- // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- //////////////////////////////////////////////////////////////////////////////////////
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var EgretWebGLUniform = (function () {
- function EgretWebGLUniform(gl, program, uniformData) {
- this.gl = gl;
- this.name = uniformData.name;
- this.type = uniformData.type;
- this.size = uniformData.size;
- this.location = gl.getUniformLocation(program, this.name);
- this.setDefaultValue();
- this.generateSetValue();
- this.generateUpload();
- }
- EgretWebGLUniform.prototype.setDefaultValue = function () {
- var type = this.type;
- switch (type) {
- case 5126 /* FLOAT */:
- case 35678 /* SAMPLER_2D */:
- case 35680 /* SAMPLER_CUBE */:
- case 35670 /* BOOL */:
- case 5124 /* INT */:
- this.value = 0;
- break;
- case 35664 /* FLOAT_VEC2 */:
- case 35671 /* BOOL_VEC2 */:
- case 35667 /* INT_VEC2 */:
- this.value = [0, 0];
- break;
- case 35665 /* FLOAT_VEC3 */:
- case 35672 /* BOOL_VEC3 */:
- case 35668 /* INT_VEC3 */:
- this.value = [0, 0, 0];
- break;
- case 35666 /* FLOAT_VEC4 */:
- case 35673 /* BOOL_VEC4 */:
- case 35669 /* INT_VEC4 */:
- this.value = [0, 0, 0, 0];
- break;
- case 35674 /* FLOAT_MAT2 */:
- this.value = new Float32Array([
- 1, 0,
- 0, 1
- ]);
- break;
- case 35675 /* FLOAT_MAT3 */:
- this.value = new Float32Array([
- 1, 0, 0,
- 0, 1, 0,
- 0, 0, 1
- ]);
- break;
- case 35676 /* FLOAT_MAT4 */:
- this.value = new Float32Array([
- 1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1
- ]);
- break;
- }
- };
- EgretWebGLUniform.prototype.generateSetValue = function () {
- var type = this.type;
- switch (type) {
- case 5126 /* FLOAT */:
- case 35678 /* SAMPLER_2D */:
- case 35680 /* SAMPLER_CUBE */:
- case 35670 /* BOOL */:
- case 5124 /* INT */:
- this.setValue = function (value) {
- var notEqual = this.value !== value;
- this.value = value;
- notEqual && this.upload();
- };
- break;
- case 35664 /* FLOAT_VEC2 */:
- case 35671 /* BOOL_VEC2 */:
- case 35667 /* INT_VEC2 */:
- this.setValue = function (value) {
- var notEqual = this.value[0] !== value.x || this.value[1] !== value.y;
- this.value[0] = value.x;
- this.value[1] = value.y;
- notEqual && this.upload();
- };
- break;
- case 35665 /* FLOAT_VEC3 */:
- case 35672 /* BOOL_VEC3 */:
- case 35668 /* INT_VEC3 */:
- this.setValue = function (value) {
- this.value[0] = value.x;
- this.value[1] = value.y;
- this.value[2] = value.z;
- this.upload();
- };
- break;
- case 35666 /* FLOAT_VEC4 */:
- case 35673 /* BOOL_VEC4 */:
- case 35669 /* INT_VEC4 */:
- this.setValue = function (value) {
- this.value[0] = value.x;
- this.value[1] = value.y;
- this.value[2] = value.z;
- this.value[3] = value.w;
- this.upload();
- };
- break;
- case 35674 /* FLOAT_MAT2 */:
- case 35675 /* FLOAT_MAT3 */:
- case 35676 /* FLOAT_MAT4 */:
- this.setValue = function (value) {
- this.value.set(value);
- this.upload();
- };
- break;
- }
- };
- EgretWebGLUniform.prototype.generateUpload = function () {
- var gl = this.gl;
- var type = this.type;
- var location = this.location;
- switch (type) {
- case 5126 /* FLOAT */:
- this.upload = function () {
- var value = this.value;
- gl.uniform1f(location, value);
- };
- break;
- case 35664 /* FLOAT_VEC2 */:
- this.upload = function () {
- var value = this.value;
- gl.uniform2f(location, value[0], value[1]);
- };
- break;
- case 35665 /* FLOAT_VEC3 */:
- this.upload = function () {
- var value = this.value;
- gl.uniform3f(location, value[0], value[1], value[2]);
- };
- break;
- case 35666 /* FLOAT_VEC4 */:
- this.upload = function () {
- var value = this.value;
- gl.uniform4f(location, value[0], value[1], value[2], value[3]);
- };
- break;
- case 35678 /* SAMPLER_2D */:
- case 35680 /* SAMPLER_CUBE */:
- case 35670 /* BOOL */:
- case 5124 /* INT */:
- this.upload = function () {
- var value = this.value;
- gl.uniform1i(location, value);
- };
- break;
- case 35671 /* BOOL_VEC2 */:
- case 35667 /* INT_VEC2 */:
- this.upload = function () {
- var value = this.value;
- gl.uniform2i(location, value[0], value[1]);
- };
- break;
- case 35672 /* BOOL_VEC3 */:
- case 35668 /* INT_VEC3 */:
- this.upload = function () {
- var value = this.value;
- gl.uniform3i(location, value[0], value[1], value[2]);
- };
- break;
- case 35673 /* BOOL_VEC4 */:
- case 35669 /* INT_VEC4 */:
- this.upload = function () {
- var value = this.value;
- gl.uniform4i(location, value[0], value[1], value[2], value[3]);
- };
- break;
- case 35674 /* FLOAT_MAT2 */:
- this.upload = function () {
- var value = this.value;
- gl.uniformMatrix2fv(location, false, value);
- };
- break;
- case 35675 /* FLOAT_MAT3 */:
- this.upload = function () {
- var value = this.value;
- gl.uniformMatrix3fv(location, false, value);
- };
- break;
- case 35676 /* FLOAT_MAT4 */:
- this.upload = function () {
- var value = this.value;
- gl.uniformMatrix4fv(location, false, value);
- };
- break;
- }
- };
- return EgretWebGLUniform;
- }());
- web.EgretWebGLUniform = EgretWebGLUniform;
- __reflect(EgretWebGLUniform.prototype, "egret.web.EgretWebGLUniform");
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- var egret;
- (function (egret) {
- var web;
- (function (web) {
- /**
- * @private
- */
- var EgretShaderLib = (function () {
- function EgretShaderLib() {
- }
- EgretShaderLib.blur_frag = "precision mediump float;\r\nuniform vec2 blur;\r\nuniform sampler2D uSampler;\r\nvarying vec2 vTextureCoord;\r\nuniform vec2 uTextureSize;\r\nvoid main()\r\n{\r\n const int sampleRadius = 5;\r\n const int samples = sampleRadius * 2 + 1;\r\n vec2 blurUv = blur / uTextureSize;\r\n vec4 color = vec4(0, 0, 0, 0);\r\n vec2 uv = vec2(0.0, 0.0);\r\n blurUv /= float(sampleRadius);\r\n\r\n for (int i = -sampleRadius; i <= sampleRadius; i++) {\r\n uv.x = vTextureCoord.x + float(i) * blurUv.x;\r\n uv.y = vTextureCoord.y + float(i) * blurUv.y;\r\n color += texture2D(uSampler, uv);\r\n }\r\n\r\n color /= float(samples);\r\n gl_FragColor = color;\r\n}";
- EgretShaderLib.colorTransform_frag = "precision mediump float;\r\nvarying vec2 vTextureCoord;\r\nvarying vec4 vColor;\r\nuniform mat4 matrix;\r\nuniform vec4 colorAdd;\r\nuniform sampler2D uSampler;\r\n\r\nvoid main(void) {\r\n vec4 texColor = texture2D(uSampler, vTextureCoord);\r\n if(texColor.a > 0.) {\r\n // 抵消预乘的alpha通道\r\n texColor = vec4(texColor.rgb / texColor.a, texColor.a);\r\n }\r\n vec4 locColor = clamp(texColor * matrix + colorAdd, 0., 1.);\r\n gl_FragColor = vColor * vec4(locColor.rgb * locColor.a, locColor.a);\r\n}";
- EgretShaderLib.default_vert = "attribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\nattribute vec2 aColor;\r\n\r\nuniform vec2 projectionVector;\r\n// uniform vec2 offsetVector;\r\n\r\nvarying vec2 vTextureCoord;\r\nvarying vec4 vColor;\r\n\r\nconst vec2 center = vec2(-1.0, 1.0);\r\n\r\nvoid main(void) {\r\n gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\r\n vTextureCoord = aTextureCoord;\r\n vColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);\r\n}";
- EgretShaderLib.glow_frag = "precision highp float;\r\nvarying vec2 vTextureCoord;\r\n\r\nuniform sampler2D uSampler;\r\n\r\nuniform float dist;\r\nuniform float angle;\r\nuniform vec4 color;\r\nuniform float alpha;\r\nuniform float blurX;\r\nuniform float blurY;\r\n// uniform vec4 quality;\r\nuniform float strength;\r\nuniform float inner;\r\nuniform float knockout;\r\nuniform float hideObject;\r\n\r\nuniform vec2 uTextureSize;\r\n\r\nfloat random(vec2 scale)\r\n{\r\n return fract(sin(dot(gl_FragCoord.xy, scale)) * 43758.5453);\r\n}\r\n\r\nvoid main(void) {\r\n vec2 px = vec2(1.0 / uTextureSize.x, 1.0 / uTextureSize.y);\r\n // TODO 自动调节采样次数?\r\n const float linearSamplingTimes = 7.0;\r\n const float circleSamplingTimes = 12.0;\r\n vec4 ownColor = texture2D(uSampler, vTextureCoord);\r\n vec4 curColor;\r\n float totalAlpha = 0.0;\r\n float maxTotalAlpha = 0.0;\r\n float curDistanceX = 0.0;\r\n float curDistanceY = 0.0;\r\n float offsetX = dist * cos(angle) * px.x;\r\n float offsetY = dist * sin(angle) * px.y;\r\n\r\n const float PI = 3.14159265358979323846264;\r\n float cosAngle;\r\n float sinAngle;\r\n float offset = PI * 2.0 / circleSamplingTimes * random(vec2(12.9898, 78.233));\r\n float stepX = blurX * px.x / linearSamplingTimes;\r\n float stepY = blurY * px.y / linearSamplingTimes;\r\n for (float a = 0.0; a <= PI * 2.0; a += PI * 2.0 / circleSamplingTimes) {\r\n cosAngle = cos(a + offset);\r\n sinAngle = sin(a + offset);\r\n for (float i = 1.0; i <= linearSamplingTimes; i++) {\r\n curDistanceX = i * stepX * cosAngle;\r\n curDistanceY = i * stepY * sinAngle;\r\n if (vTextureCoord.x + curDistanceX - offsetX >= 0.0 && vTextureCoord.y + curDistanceY + offsetY <= 1.0){\r\n curColor = texture2D(uSampler, vec2(vTextureCoord.x + curDistanceX - offsetX, vTextureCoord.y + curDistanceY + offsetY));\r\n totalAlpha += (linearSamplingTimes - i) * curColor.a;\r\n }\r\n maxTotalAlpha += (linearSamplingTimes - i);\r\n }\r\n }\r\n\r\n ownColor.a = max(ownColor.a, 0.0001);\r\n ownColor.rgb = ownColor.rgb / ownColor.a;\r\n\r\n float outerGlowAlpha = (totalAlpha / maxTotalAlpha) * strength * alpha * (1. - inner) * max(min(hideObject, knockout), 1. - ownColor.a);\r\n float innerGlowAlpha = ((maxTotalAlpha - totalAlpha) / maxTotalAlpha) * strength * alpha * inner * ownColor.a;\r\n\r\n ownColor.a = max(ownColor.a * knockout * (1. - hideObject), 0.0001);\r\n vec3 mix1 = mix(ownColor.rgb, color.rgb, innerGlowAlpha / (innerGlowAlpha + ownColor.a));\r\n vec3 mix2 = mix(mix1, color.rgb, outerGlowAlpha / (innerGlowAlpha + ownColor.a + outerGlowAlpha));\r\n float resultAlpha = min(ownColor.a + outerGlowAlpha + innerGlowAlpha, 1.);\r\n gl_FragColor = vec4(mix2 * resultAlpha, resultAlpha);\r\n}";
- EgretShaderLib.primitive_frag = "precision lowp float;\r\nvarying vec2 vTextureCoord;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n gl_FragColor = vColor;\r\n}";
- EgretShaderLib.texture_frag = "precision lowp float;\r\nvarying vec2 vTextureCoord;\r\nvarying vec4 vColor;\r\nuniform sampler2D uSampler;\r\n\r\nvoid main(void) {\r\n gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;\r\n}";
- return EgretShaderLib;
- }());
- web.EgretShaderLib = EgretShaderLib;
- __reflect(EgretShaderLib.prototype, "egret.web.EgretShaderLib");
- })(web = egret.web || (egret.web = {}));
- })(egret || (egret = {}));
- ;
|