softgames_game.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865
  1. !function(root, factory) {
  2. if (typeof define === "function" && define.amd) {
  3. define(factory);
  4. } else if (typeof exports === "object") {
  5. module.exports = factory();
  6. } else {
  7. root.Phaser = factory();
  8. }
  9. }(this, function() {
  10. /**
  11. * @author Richard Davey <rich@photonstorm.com>
  12. * @copyright 2013 Photon Storm Ltd.
  13. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  14. */
  15. /**
  16. * @overview
  17. *
  18. * Phaser - http://www.phaser.io
  19. *
  20. * v1.1.3 - Built at: Fri Nov 29 2013 18:20:59
  21. *
  22. * By Richard Davey http://www.photonstorm.com @photonstorm
  23. *
  24. * A feature-packed 2D HTML5 game framework born from the smouldering pits of Flixel and
  25. * constructed via plenty of blood, sweat, tears and coffee by Richard Davey (@photonstorm).
  26. *
  27. * Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com/ @Doormat23.
  28. *
  29. * Follow Phaser development progress at http://www.photonstorm.com
  30. *
  31. * Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from both which Phaser
  32. * and my love of game development originate.
  33. *
  34. * "If you want your children to be intelligent, read them fairy tales."
  35. * "If you want them to be more intelligent, read them more fairy tales."
  36. * -- Albert Einstein
  37. */
  38. /**
  39. * @author Mat Groves http://matgroves.com/ @Doormat23
  40. */
  41. /**
  42. * @module PIXI
  43. */
  44. var PIXI = PIXI || {};
  45. /**
  46. * @author Richard Davey <rich@photonstorm.com>
  47. * @copyright 2013 Photon Storm Ltd.
  48. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  49. */
  50. /**
  51. * @namespace Phaser
  52. */
  53. var Phaser = Phaser || {
  54. VERSION: '1.1.3',
  55. DEV_VERSION: '1.1.3',
  56. GAMES: [],
  57. AUTO: 0,
  58. CANVAS: 1,
  59. WEBGL: 2,
  60. HEADLESS: 3,
  61. SPRITE: 0,
  62. BUTTON: 1,
  63. BULLET: 2,
  64. GRAPHICS: 3,
  65. TEXT: 4,
  66. TILESPRITE: 5,
  67. BITMAPTEXT: 6,
  68. GROUP: 7,
  69. RENDERTEXTURE: 8,
  70. TILEMAP: 9,
  71. TILEMAPLAYER: 10,
  72. EMITTER: 11,
  73. POLYGON: 12,
  74. BITMAPDATA: 13,
  75. CANVAS_FILTER: 14,
  76. WEBGL_FILTER: 15,
  77. NONE: 0,
  78. LEFT: 1,
  79. RIGHT: 2,
  80. UP: 3,
  81. DOWN: 4
  82. };
  83. PIXI.InteractionManager = function (dummy) {
  84. // We don't need this in Pixi, so we've removed it to save space
  85. // however the Stage object expects a reference to it, so here is a dummy entry.
  86. };
  87. /* jshint supernew: true */
  88. /**
  89. * @author Richard Davey <rich@photonstorm.com>
  90. * @copyright 2013 Photon Storm Ltd.
  91. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  92. */
  93. /**
  94. * @class Phaser.Utils
  95. * @static
  96. */
  97. Phaser.Utils = {
  98. /**
  99. * A standard Fisher-Yates Array shuffle implementation.
  100. * @method Phaser.Utils.shuffle
  101. * @param {array} array - The array to shuffle.
  102. * @return {array} The shuffled array.
  103. */
  104. shuffle: function (array) {
  105. for (var i = array.length - 1; i > 0; i--)
  106. {
  107. var j = Math.floor(Math.random() * (i + 1));
  108. var temp = array[i];
  109. array[i] = array[j];
  110. array[j] = temp;
  111. }
  112. return array;
  113. },
  114. /**
  115. * Javascript string pad http://www.webtoolkit.info/.
  116. * pad = the string to pad it out with (defaults to a space)
  117. * dir = 1 (left), 2 (right), 3 (both)
  118. * @method Phaser.Utils.pad
  119. * @param {string} str - The target string.
  120. * @param {number} len - Description.
  121. * @param {number} pad - the string to pad it out with (defaults to a space).
  122. * @param {number} [dir=3] the direction dir = 1 (left), 2 (right), 3 (both).
  123. * @return {string} The padded string
  124. */
  125. pad: function (str, len, pad, dir) {
  126. if (typeof(len) == "undefined") { var len = 0; }
  127. if (typeof(pad) == "undefined") { var pad = ' '; }
  128. if (typeof(dir) == "undefined") { var dir = 3; }
  129. var padlen = 0;
  130. if (len + 1 >= str.length)
  131. {
  132. switch (dir)
  133. {
  134. case 1:
  135. str = Array(len + 1 - str.length).join(pad) + str;
  136. break;
  137. case 3:
  138. var right = Math.ceil((padlen = len - str.length) / 2);
  139. var left = padlen - right;
  140. str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
  141. break;
  142. default:
  143. str = str + Array(len + 1 - str.length).join(pad);
  144. break;
  145. }
  146. }
  147. return str;
  148. },
  149. /**
  150. * This is a slightly modified version of jQuery.isPlainObject. A plain object is an object whose internal class property is [object Object].
  151. * @method Phaser.Utils.isPlainObject
  152. * @param {object} obj - The object to inspect.
  153. * @return {boolean} - true if the object is plain, otherwise false.
  154. */
  155. isPlainObject: function (obj) {
  156. // Not plain objects:
  157. // - Any object or value whose internal [[Class]] property is not "[object Object]"
  158. // - DOM nodes
  159. // - window
  160. if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window)
  161. {
  162. return false;
  163. }
  164. // Support: Firefox <20
  165. // The try/catch suppresses exceptions thrown when attempting to access
  166. // the "constructor" property of certain host objects, ie. |window.location|
  167. // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
  168. try {
  169. if (obj.constructor && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf"))
  170. {
  171. return false;
  172. }
  173. } catch (e) {
  174. return false;
  175. }
  176. // If the function hasn't returned already, we're confident that
  177. // |obj| is a plain object, created by {} or constructed with new Object
  178. return true;
  179. },
  180. // deep, target, objects to copy to the target object
  181. // This is a slightly modified version of {@link http://api.jquery.com/jQuery.extend/|jQuery.extend}
  182. // deep (boolean)
  183. // target (object to add to)
  184. // objects ... (objects to recurse and copy from)
  185. /**
  186. * This is a slightly modified version of http://api.jquery.com/jQuery.extend/
  187. * @method Phaser.Utils.extend
  188. * @param {boolean} deep - Perform a deep copy?
  189. * @param {object} target - The target object to copy to.
  190. * @return {object} The extended object.
  191. */
  192. extend: function () {
  193. var options, name, src, copy, copyIsArray, clone,
  194. target = arguments[0] || {},
  195. i = 1,
  196. length = arguments.length,
  197. deep = false;
  198. // Handle a deep copy situation
  199. if (typeof target === "boolean")
  200. {
  201. deep = target;
  202. target = arguments[1] || {};
  203. // skip the boolean and the target
  204. i = 2;
  205. }
  206. // extend Phaser if only one argument is passed
  207. if (length === i)
  208. {
  209. target = this;
  210. --i;
  211. }
  212. for ( ; i < length; i++ )
  213. {
  214. // Only deal with non-null/undefined values
  215. if ((options = arguments[i]) != null)
  216. {
  217. // Extend the base object
  218. for (name in options)
  219. {
  220. src = target[name];
  221. copy = options[name];
  222. // Prevent never-ending loop
  223. if (target === copy)
  224. {
  225. continue;
  226. }
  227. // Recurse if we're merging plain objects or arrays
  228. if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy))))
  229. {
  230. if (copyIsArray)
  231. {
  232. copyIsArray = false;
  233. clone = src && Array.isArray(src) ? src : [];
  234. }
  235. else
  236. {
  237. clone = src && Phaser.Utils.isPlainObject(src) ? src : {};
  238. }
  239. // Never move original objects, clone them
  240. target[name] = Phaser.Utils.extend(deep, clone, copy);
  241. // Don't bring in undefined values
  242. }
  243. else if (copy !== undefined)
  244. {
  245. target[name] = copy;
  246. }
  247. }
  248. }
  249. }
  250. // Return the modified object
  251. return target;
  252. }
  253. };
  254. // Global functions that PIXI needs
  255. (function() {
  256. var consoleDisabled = false;
  257. if (consoleDisabled) {
  258. window.console = undefined;
  259. }
  260. if (window.console === undefined) {
  261. window.console = {
  262. debug: function() {
  263. return true;
  264. },
  265. info: function() {
  266. return false;
  267. },
  268. warn: function() {
  269. return false;
  270. },
  271. log: function() {
  272. return false;
  273. }
  274. }
  275. }
  276. debug = (function(args) {
  277. window.console.debug(args);
  278. });
  279. info = (function(args) {
  280. window.console.info(args);
  281. });
  282. warn = (function(args) {
  283. window.console.warn(args);
  284. });
  285. log = (function(args) {
  286. window.console.log(args);
  287. });
  288. })();
  289. /**
  290. * Converts a hex color number to an [R, G, B] array
  291. *
  292. * @param {number} hex
  293. * @return {array}
  294. */
  295. function HEXtoRGB(hex) {
  296. return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255];
  297. }
  298. /**
  299. * A polyfill for Function.prototype.bind
  300. */
  301. if (typeof Function.prototype.bind != 'function') {
  302. Function.prototype.bind = (function () {
  303. var slice = Array.prototype.slice;
  304. return function (thisArg) {
  305. var target = this, boundArgs = slice.call(arguments, 1);
  306. if (typeof target != 'function')
  307. {
  308. throw new TypeError();
  309. }
  310. function bound() {
  311. var args = boundArgs.concat(slice.call(arguments));
  312. target.apply(this instanceof bound ? this : thisArg, args);
  313. }
  314. bound.prototype = (function F(proto) {
  315. proto && (F.prototype = proto);
  316. if (!(this instanceof F))
  317. {
  318. return new F;
  319. }
  320. })(target.prototype);
  321. return bound;
  322. };
  323. })();
  324. }
  325. /*
  326. * A lighter version of the rad gl-matrix created by Brandon Jones, Colin MacKenzie IV
  327. * you both rock!
  328. */
  329. function determineMatrixArrayType() {
  330. PIXI.Matrix = (typeof Float32Array !== 'undefined') ? Float32Array : Array;
  331. return PIXI.Matrix;
  332. }
  333. determineMatrixArrayType();
  334. PIXI.mat3 = {};
  335. PIXI.mat3.create = function()
  336. {
  337. var matrix = new PIXI.Matrix(9);
  338. matrix[0] = 1;
  339. matrix[1] = 0;
  340. matrix[2] = 0;
  341. matrix[3] = 0;
  342. matrix[4] = 1;
  343. matrix[5] = 0;
  344. matrix[6] = 0;
  345. matrix[7] = 0;
  346. matrix[8] = 1;
  347. return matrix;
  348. }
  349. PIXI.mat3.identity = function(matrix)
  350. {
  351. matrix[0] = 1;
  352. matrix[1] = 0;
  353. matrix[2] = 0;
  354. matrix[3] = 0;
  355. matrix[4] = 1;
  356. matrix[5] = 0;
  357. matrix[6] = 0;
  358. matrix[7] = 0;
  359. matrix[8] = 1;
  360. return matrix;
  361. }
  362. PIXI.mat4 = {};
  363. PIXI.mat4.create = function()
  364. {
  365. var matrix = new PIXI.Matrix(16);
  366. matrix[0] = 1;
  367. matrix[1] = 0;
  368. matrix[2] = 0;
  369. matrix[3] = 0;
  370. matrix[4] = 0;
  371. matrix[5] = 1;
  372. matrix[6] = 0;
  373. matrix[7] = 0;
  374. matrix[8] = 0;
  375. matrix[9] = 0;
  376. matrix[10] = 1;
  377. matrix[11] = 0;
  378. matrix[12] = 0;
  379. matrix[13] = 0;
  380. matrix[14] = 0;
  381. matrix[15] = 1;
  382. return matrix;
  383. }
  384. PIXI.mat3.multiply = function (mat, mat2, dest)
  385. {
  386. if (!dest) { dest = mat; }
  387. // Cache the matrix values (makes for huge speed increases!)
  388. var a00 = mat[0], a01 = mat[1], a02 = mat[2],
  389. a10 = mat[3], a11 = mat[4], a12 = mat[5],
  390. a20 = mat[6], a21 = mat[7], a22 = mat[8],
  391. b00 = mat2[0], b01 = mat2[1], b02 = mat2[2],
  392. b10 = mat2[3], b11 = mat2[4], b12 = mat2[5],
  393. b20 = mat2[6], b21 = mat2[7], b22 = mat2[8];
  394. dest[0] = b00 * a00 + b01 * a10 + b02 * a20;
  395. dest[1] = b00 * a01 + b01 * a11 + b02 * a21;
  396. dest[2] = b00 * a02 + b01 * a12 + b02 * a22;
  397. dest[3] = b10 * a00 + b11 * a10 + b12 * a20;
  398. dest[4] = b10 * a01 + b11 * a11 + b12 * a21;
  399. dest[5] = b10 * a02 + b11 * a12 + b12 * a22;
  400. dest[6] = b20 * a00 + b21 * a10 + b22 * a20;
  401. dest[7] = b20 * a01 + b21 * a11 + b22 * a21;
  402. dest[8] = b20 * a02 + b21 * a12 + b22 * a22;
  403. return dest;
  404. }
  405. PIXI.mat3.clone = function(mat)
  406. {
  407. var matrix = new PIXI.Matrix(9);
  408. matrix[0] = mat[0];
  409. matrix[1] = mat[1];
  410. matrix[2] = mat[2];
  411. matrix[3] = mat[3];
  412. matrix[4] = mat[4];
  413. matrix[5] = mat[5];
  414. matrix[6] = mat[6];
  415. matrix[7] = mat[7];
  416. matrix[8] = mat[8];
  417. return matrix;
  418. }
  419. PIXI.mat3.transpose = function (mat, dest)
  420. {
  421. // If we are transposing ourselves we can skip a few steps but have to cache some values
  422. if (!dest || mat === dest) {
  423. var a01 = mat[1], a02 = mat[2],
  424. a12 = mat[5];
  425. mat[1] = mat[3];
  426. mat[2] = mat[6];
  427. mat[3] = a01;
  428. mat[5] = mat[7];
  429. mat[6] = a02;
  430. mat[7] = a12;
  431. return mat;
  432. }
  433. dest[0] = mat[0];
  434. dest[1] = mat[3];
  435. dest[2] = mat[6];
  436. dest[3] = mat[1];
  437. dest[4] = mat[4];
  438. dest[5] = mat[7];
  439. dest[6] = mat[2];
  440. dest[7] = mat[5];
  441. dest[8] = mat[8];
  442. return dest;
  443. }
  444. PIXI.mat3.toMat4 = function (mat, dest)
  445. {
  446. if (!dest) { dest = PIXI.mat4.create(); }
  447. dest[15] = 1;
  448. dest[14] = 0;
  449. dest[13] = 0;
  450. dest[12] = 0;
  451. dest[11] = 0;
  452. dest[10] = mat[8];
  453. dest[9] = mat[7];
  454. dest[8] = mat[6];
  455. dest[7] = 0;
  456. dest[6] = mat[5];
  457. dest[5] = mat[4];
  458. dest[4] = mat[3];
  459. dest[3] = 0;
  460. dest[2] = mat[2];
  461. dest[1] = mat[1];
  462. dest[0] = mat[0];
  463. return dest;
  464. }
  465. /////
  466. PIXI.mat4.create = function()
  467. {
  468. var matrix = new PIXI.Matrix(16);
  469. matrix[0] = 1;
  470. matrix[1] = 0;
  471. matrix[2] = 0;
  472. matrix[3] = 0;
  473. matrix[4] = 0;
  474. matrix[5] = 1;
  475. matrix[6] = 0;
  476. matrix[7] = 0;
  477. matrix[8] = 0;
  478. matrix[9] = 0;
  479. matrix[10] = 1;
  480. matrix[11] = 0;
  481. matrix[12] = 0;
  482. matrix[13] = 0;
  483. matrix[14] = 0;
  484. matrix[15] = 1;
  485. return matrix;
  486. }
  487. PIXI.mat4.transpose = function (mat, dest)
  488. {
  489. // If we are transposing ourselves we can skip a few steps but have to cache some values
  490. if (!dest || mat === dest)
  491. {
  492. var a01 = mat[1], a02 = mat[2], a03 = mat[3],
  493. a12 = mat[6], a13 = mat[7],
  494. a23 = mat[11];
  495. mat[1] = mat[4];
  496. mat[2] = mat[8];
  497. mat[3] = mat[12];
  498. mat[4] = a01;
  499. mat[6] = mat[9];
  500. mat[7] = mat[13];
  501. mat[8] = a02;
  502. mat[9] = a12;
  503. mat[11] = mat[14];
  504. mat[12] = a03;
  505. mat[13] = a13;
  506. mat[14] = a23;
  507. return mat;
  508. }
  509. dest[0] = mat[0];
  510. dest[1] = mat[4];
  511. dest[2] = mat[8];
  512. dest[3] = mat[12];
  513. dest[4] = mat[1];
  514. dest[5] = mat[5];
  515. dest[6] = mat[9];
  516. dest[7] = mat[13];
  517. dest[8] = mat[2];
  518. dest[9] = mat[6];
  519. dest[10] = mat[10];
  520. dest[11] = mat[14];
  521. dest[12] = mat[3];
  522. dest[13] = mat[7];
  523. dest[14] = mat[11];
  524. dest[15] = mat[15];
  525. return dest;
  526. }
  527. PIXI.mat4.multiply = function (mat, mat2, dest)
  528. {
  529. if (!dest) { dest = mat; }
  530. // Cache the matrix values (makes for huge speed increases!)
  531. var a00 = mat[ 0], a01 = mat[ 1], a02 = mat[ 2], a03 = mat[3];
  532. var a10 = mat[ 4], a11 = mat[ 5], a12 = mat[ 6], a13 = mat[7];
  533. var a20 = mat[ 8], a21 = mat[ 9], a22 = mat[10], a23 = mat[11];
  534. var a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15];
  535. // Cache only the current line of the second matrix
  536. var b0 = mat2[0], b1 = mat2[1], b2 = mat2[2], b3 = mat2[3];
  537. dest[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
  538. dest[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
  539. dest[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
  540. dest[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
  541. b0 = mat2[4];
  542. b1 = mat2[5];
  543. b2 = mat2[6];
  544. b3 = mat2[7];
  545. dest[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
  546. dest[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
  547. dest[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
  548. dest[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
  549. b0 = mat2[8];
  550. b1 = mat2[9];
  551. b2 = mat2[10];
  552. b3 = mat2[11];
  553. dest[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
  554. dest[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
  555. dest[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
  556. dest[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
  557. b0 = mat2[12];
  558. b1 = mat2[13];
  559. b2 = mat2[14];
  560. b3 = mat2[15];
  561. dest[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
  562. dest[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
  563. dest[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
  564. dest[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
  565. return dest;
  566. }
  567. /**
  568. * @author Mat Groves http://matgroves.com/ @Doormat23
  569. */
  570. /**
  571. * The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
  572. *
  573. * @class Point
  574. * @constructor
  575. * @param x {Number} position of the point
  576. * @param y {Number} position of the point
  577. */
  578. PIXI.Point = function(x, y)
  579. {
  580. /**
  581. * @property x
  582. * @type Number
  583. * @default 0
  584. */
  585. this.x = x || 0;
  586. /**
  587. * @property y
  588. * @type Number
  589. * @default 0
  590. */
  591. this.y = y || 0;
  592. }
  593. /**
  594. * Creates a clone of this point
  595. *
  596. * @method clone
  597. * @return {Point} a copy of the point
  598. */
  599. PIXI.Point.prototype.clone = function()
  600. {
  601. return new PIXI.Point(this.x, this.y);
  602. }
  603. // constructor
  604. PIXI.Point.prototype.constructor = PIXI.Point;
  605. /**
  606. * @author Mat Groves http://matgroves.com/
  607. */
  608. /**
  609. * the Rectangle object is an area defined by its position, as indicated by its top-left corner point (x, y) and by its width and its height.
  610. *
  611. * @class Rectangle
  612. * @constructor
  613. * @param x {Number} The X coord of the upper-left corner of the rectangle
  614. * @param y {Number} The Y coord of the upper-left corner of the rectangle
  615. * @param width {Number} The overall width of this rectangle
  616. * @param height {Number} The overall height of this rectangle
  617. */
  618. PIXI.Rectangle = function(x, y, width, height)
  619. {
  620. /**
  621. * @property x
  622. * @type Number
  623. * @default 0
  624. */
  625. this.x = x || 0;
  626. /**
  627. * @property y
  628. * @type Number
  629. * @default 0
  630. */
  631. this.y = y || 0;
  632. /**
  633. * @property width
  634. * @type Number
  635. * @default 0
  636. */
  637. this.width = width || 0;
  638. /**
  639. * @property height
  640. * @type Number
  641. * @default 0
  642. */
  643. this.height = height || 0;
  644. }
  645. /**
  646. * Creates a clone of this Rectangle
  647. *
  648. * @method clone
  649. * @return {Rectangle} a copy of the rectangle
  650. */
  651. PIXI.Rectangle.prototype.clone = function()
  652. {
  653. return new PIXI.Rectangle(this.x, this.y, this.width, this.height);
  654. }
  655. /**
  656. * Checks if the x, and y coords passed to this function are contained within this Rectangle
  657. *
  658. * @method contains
  659. * @param x {Number} The X coord of the point to test
  660. * @param y {Number} The Y coord of the point to test
  661. * @return {Boolean} if the x/y coords are within this Rectangle
  662. */
  663. PIXI.Rectangle.prototype.contains = function(x, y)
  664. {
  665. if(this.width <= 0 || this.height <= 0)
  666. return false;
  667. var x1 = this.x;
  668. if(x >= x1 && x <= x1 + this.width)
  669. {
  670. var y1 = this.y;
  671. if(y >= y1 && y <= y1 + this.height)
  672. {
  673. return true;
  674. }
  675. }
  676. return false;
  677. }
  678. // constructor
  679. PIXI.Rectangle.prototype.constructor = PIXI.Rectangle;
  680. /**
  681. * @author Adrien Brault <adrien.brault@gmail.com>
  682. */
  683. /**
  684. * @class Polygon
  685. * @constructor
  686. * @param points* {Array<Point>|Array<Number>|Point...|Number...} This can be an array of Points that form the polygon,
  687. * a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be
  688. * all the points of the polygon e.g. `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the
  689. * arguments passed can be flat x,y values e.g. `new PIXI.Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are
  690. * Numbers.
  691. */
  692. PIXI.Polygon = function(points)
  693. {
  694. //if points isn't an array, use arguments as the array
  695. if(!(points instanceof Array))
  696. points = Array.prototype.slice.call(arguments);
  697. //if this is a flat array of numbers, convert it to points
  698. if(typeof points[0] === 'number') {
  699. var p = [];
  700. for(var i = 0, il = points.length; i < il; i+=2) {
  701. p.push(
  702. new PIXI.Point(points[i], points[i + 1])
  703. );
  704. }
  705. points = p;
  706. }
  707. this.points = points;
  708. }
  709. /**
  710. * Creates a clone of this polygon
  711. *
  712. * @method clone
  713. * @return {Polygon} a copy of the polygon
  714. */
  715. PIXI.Polygon.prototype.clone = function()
  716. {
  717. var points = [];
  718. for (var i=0; i<this.points.length; i++) {
  719. points.push(this.points[i].clone());
  720. }
  721. return new PIXI.Polygon(points);
  722. }
  723. /**
  724. * Checks if the x, and y coords passed to this function are contained within this polygon
  725. *
  726. * @method contains
  727. * @param x {Number} The X coord of the point to test
  728. * @param y {Number} The Y coord of the point to test
  729. * @return {Boolean} if the x/y coords are within this polygon
  730. */
  731. PIXI.Polygon.prototype.contains = function(x, y)
  732. {
  733. var inside = false;
  734. // use some raycasting to test hits
  735. // https://github.com/substack/point-in-polygon/blob/master/index.js
  736. for(var i = 0, j = this.points.length - 1; i < this.points.length; j = i++) {
  737. var xi = this.points[i].x, yi = this.points[i].y,
  738. xj = this.points[j].x, yj = this.points[j].y,
  739. intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
  740. if(intersect) inside = !inside;
  741. }
  742. return inside;
  743. }
  744. // constructor
  745. PIXI.Polygon.prototype.constructor = PIXI.Polygon;
  746. /**
  747. * @author Mat Groves http://matgroves.com/ @Doormat23
  748. */
  749. /**
  750. * The base class for all objects that are rendered on the screen.
  751. *
  752. * @class DisplayObject
  753. * @constructor
  754. */
  755. PIXI.DisplayObject = function()
  756. {
  757. this.last = this;
  758. this.first = this;
  759. /**
  760. * The coordinate of the object relative to the local coordinates of the parent.
  761. *
  762. * @property position
  763. * @type Point
  764. */
  765. this.position = new PIXI.Point();
  766. /**
  767. * The scale factor of the object.
  768. *
  769. * @property scale
  770. * @type Point
  771. */
  772. this.scale = new PIXI.Point(1,1);//{x:1, y:1};
  773. /**
  774. * The pivot point of the displayObject that it rotates around
  775. *
  776. * @property pivot
  777. * @type Point
  778. */
  779. this.pivot = new PIXI.Point(0,0);
  780. /**
  781. * The rotation of the object in radians.
  782. *
  783. * @property rotation
  784. * @type Number
  785. */
  786. this.rotation = 0;
  787. /**
  788. * The opacity of the object.
  789. *
  790. * @property alpha
  791. * @type Number
  792. */
  793. this.alpha = 1;
  794. /**
  795. * The visibility of the object.
  796. *
  797. * @property visible
  798. * @type Boolean
  799. */
  800. this.visible = true;
  801. /**
  802. * This is the defined area that will pick up mouse / touch events. It is null by default.
  803. * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children)
  804. *
  805. * @property hitArea
  806. * @type Rectangle|Circle|Ellipse|Polygon
  807. */
  808. this.hitArea = null;
  809. /**
  810. * This is used to indicate if the displayObject should display a mouse hand cursor on rollover
  811. *
  812. * @property buttonMode
  813. * @type Boolean
  814. */
  815. this.buttonMode = false;
  816. /**
  817. * Can this object be rendered
  818. *
  819. * @property renderable
  820. * @type Boolean
  821. */
  822. this.renderable = false;
  823. /**
  824. * [read-only] The display object container that contains this display object.
  825. *
  826. * @property parent
  827. * @type DisplayObjectContainer
  828. * @readOnly
  829. */
  830. this.parent = null;
  831. /**
  832. * [read-only] The stage the display object is connected to, or undefined if it is not connected to the stage.
  833. *
  834. * @property stage
  835. * @type Stage
  836. * @readOnly
  837. */
  838. this.stage = null;
  839. /**
  840. * [read-only] The multiplied alpha of the displayobject
  841. *
  842. * @property worldAlpha
  843. * @type Number
  844. * @readOnly
  845. */
  846. this.worldAlpha = 1;
  847. /**
  848. * [read-only] Whether or not the object is interactive, do not toggle directly! use the `interactive` property
  849. *
  850. * @property _interactive
  851. * @type Boolean
  852. * @readOnly
  853. * @private
  854. */
  855. this._interactive = false;
  856. /**
  857. * [read-only] Current transform of the object based on world (parent) factors
  858. *
  859. * @property worldTransform
  860. * @type Mat3
  861. * @readOnly
  862. * @private
  863. */
  864. this.worldTransform = PIXI.mat3.create()//mat3.identity();
  865. /**
  866. * [read-only] Current transform of the object locally
  867. *
  868. * @property localTransform
  869. * @type Mat3
  870. * @readOnly
  871. * @private
  872. */
  873. this.localTransform = PIXI.mat3.create()//mat3.identity();
  874. /**
  875. * [NYI] Unkown
  876. *
  877. * @property color
  878. * @type Array<>
  879. * @private
  880. */
  881. this.color = [];
  882. /**
  883. * [NYI] Holds whether or not this object is dynamic, for rendering optimization
  884. *
  885. * @property dynamic
  886. * @type Boolean
  887. * @private
  888. */
  889. this.dynamic = true;
  890. // chach that puppy!
  891. this._sr = 0;
  892. this._cr = 1;
  893. this.filterArea = new PIXI.Rectangle(0,0,1,1);
  894. /*
  895. * MOUSE Callbacks
  896. */
  897. /**
  898. * A callback that is used when the users clicks on the displayObject with their mouse
  899. * @method click
  900. * @param interactionData {InteractionData}
  901. */
  902. /**
  903. * A callback that is used when the user clicks the mouse down over the sprite
  904. * @method mousedown
  905. * @param interactionData {InteractionData}
  906. */
  907. /**
  908. * A callback that is used when the user releases the mouse that was over the displayObject
  909. * for this callback to be fired the mouse must have been pressed down over the displayObject
  910. * @method mouseup
  911. * @param interactionData {InteractionData}
  912. */
  913. /**
  914. * A callback that is used when the user releases the mouse that was over the displayObject but is no longer over the displayObject
  915. * for this callback to be fired, The touch must have started over the displayObject
  916. * @method mouseupoutside
  917. * @param interactionData {InteractionData}
  918. */
  919. /**
  920. * A callback that is used when the users mouse rolls over the displayObject
  921. * @method mouseover
  922. * @param interactionData {InteractionData}
  923. */
  924. /**
  925. * A callback that is used when the users mouse leaves the displayObject
  926. * @method mouseout
  927. * @param interactionData {InteractionData}
  928. */
  929. /*
  930. * TOUCH Callbacks
  931. */
  932. /**
  933. * A callback that is used when the users taps on the sprite with their finger
  934. * basically a touch version of click
  935. * @method tap
  936. * @param interactionData {InteractionData}
  937. */
  938. /**
  939. * A callback that is used when the user touch's over the displayObject
  940. * @method touchstart
  941. * @param interactionData {InteractionData}
  942. */
  943. /**
  944. * A callback that is used when the user releases a touch over the displayObject
  945. * @method touchend
  946. * @param interactionData {InteractionData}
  947. */
  948. /**
  949. * A callback that is used when the user releases the touch that was over the displayObject
  950. * for this callback to be fired, The touch must have started over the sprite
  951. * @method touchendoutside
  952. * @param interactionData {InteractionData}
  953. */
  954. }
  955. // constructor
  956. PIXI.DisplayObject.prototype.constructor = PIXI.DisplayObject;
  957. /**
  958. * [Deprecated] Indicates if the sprite will have touch and mouse interactivity. It is false by default
  959. * Instead of using this function you can now simply set the interactive property to true or false
  960. *
  961. * @method setInteractive
  962. * @param interactive {Boolean}
  963. * @deprecated Simply set the `interactive` property directly
  964. */
  965. PIXI.DisplayObject.prototype.setInteractive = function(interactive)
  966. {
  967. this.interactive = interactive;
  968. }
  969. /**
  970. * Indicates if the sprite will have touch and mouse interactivity. It is false by default
  971. *
  972. * @property interactive
  973. * @type Boolean
  974. * @default false
  975. */
  976. Object.defineProperty(PIXI.DisplayObject.prototype, 'interactive', {
  977. get: function() {
  978. return this._interactive;
  979. },
  980. set: function(value) {
  981. this._interactive = value;
  982. // TODO more to be done here..
  983. // need to sort out a re-crawl!
  984. if(this.stage)this.stage.dirty = true;
  985. }
  986. });
  987. /**
  988. * Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it.
  989. * In PIXI a regular mask must be a PIXI.Ggraphics object. This allows for much faster masking in canvas as it utilises shape clipping.
  990. * To remove a mask, set this property to null.
  991. *
  992. * @property mask
  993. * @type Graphics
  994. */
  995. Object.defineProperty(PIXI.DisplayObject.prototype, 'mask', {
  996. get: function() {
  997. return this._mask;
  998. },
  999. set: function(value) {
  1000. if(value)
  1001. {
  1002. if(this._mask)
  1003. {
  1004. value.start = this._mask.start;
  1005. value.end = this._mask.end;
  1006. }
  1007. else
  1008. {
  1009. this.addFilter(value);
  1010. value.renderable = false;
  1011. }
  1012. }
  1013. else
  1014. {
  1015. this.removeFilter(this._mask);
  1016. this._mask.renderable = true;
  1017. }
  1018. this._mask = value;
  1019. }
  1020. });
  1021. /**
  1022. * Sets the filters for the displayObject.
  1023. * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer.
  1024. * To remove filters simply set this property to 'null'
  1025. * @property filters
  1026. * @type Array An array of filters
  1027. */
  1028. Object.defineProperty(PIXI.DisplayObject.prototype, 'filters', {
  1029. get: function() {
  1030. return this._filters;
  1031. },
  1032. set: function(value) {
  1033. if(value)
  1034. {
  1035. if(this._filters)this.removeFilter(this._filters);
  1036. this.addFilter(value);
  1037. // now put all the passes in one place..
  1038. var passes = [];
  1039. for (var i = 0; i < value.length; i++)
  1040. {
  1041. var filterPasses = value[i].passes;
  1042. for (var j = 0; j < filterPasses.length; j++)
  1043. {
  1044. passes.push(filterPasses[j]);
  1045. };
  1046. };
  1047. value.start.filterPasses = passes;
  1048. }
  1049. else
  1050. {
  1051. if(this._filters)this.removeFilter(this._filters);
  1052. }
  1053. this._filters = value;
  1054. }
  1055. });
  1056. /*
  1057. * Adds a filter to this displayObject
  1058. *
  1059. * @method addFilter
  1060. * @param mask {Graphics} the graphics object to use as a filter
  1061. * @private
  1062. */
  1063. PIXI.DisplayObject.prototype.addFilter = function(data)
  1064. {
  1065. // insert a filter block..
  1066. // TODO Onject pool thease bad boys..
  1067. var start = new PIXI.FilterBlock();
  1068. var end = new PIXI.FilterBlock();
  1069. data.start = start;
  1070. data.end = end;
  1071. start.data = data;
  1072. end.data = data;
  1073. start.first = start.last = this;
  1074. end.first = end.last = this;
  1075. start.open = true;
  1076. start.target = this;
  1077. /*
  1078. * insert start
  1079. */
  1080. var childFirst = start
  1081. var childLast = start
  1082. var nextObject;
  1083. var previousObject;
  1084. previousObject = this.first._iPrev;
  1085. if(previousObject)
  1086. {
  1087. nextObject = previousObject._iNext;
  1088. childFirst._iPrev = previousObject;
  1089. previousObject._iNext = childFirst;
  1090. }
  1091. else
  1092. {
  1093. nextObject = this;
  1094. }
  1095. if(nextObject)
  1096. {
  1097. nextObject._iPrev = childLast;
  1098. childLast._iNext = nextObject;
  1099. }
  1100. // now insert the end filter block..
  1101. /*
  1102. * insert end filter
  1103. */
  1104. var childFirst = end
  1105. var childLast = end
  1106. var nextObject = null;
  1107. var previousObject = null;
  1108. previousObject = this.last;
  1109. nextObject = previousObject._iNext;
  1110. if(nextObject)
  1111. {
  1112. nextObject._iPrev = childLast;
  1113. childLast._iNext = nextObject;
  1114. }
  1115. childFirst._iPrev = previousObject;
  1116. previousObject._iNext = childFirst;
  1117. var updateLast = this;
  1118. var prevLast = this.last;
  1119. while(updateLast)
  1120. {
  1121. if(updateLast.last == prevLast)
  1122. {
  1123. updateLast.last = end;
  1124. }
  1125. updateLast = updateLast.parent;
  1126. }
  1127. this.first = start;
  1128. // if webGL...
  1129. if(this.__renderGroup)
  1130. {
  1131. this.__renderGroup.addFilterBlocks(start, end);
  1132. }
  1133. }
  1134. /*
  1135. * Removes the filter to this displayObject
  1136. *
  1137. * @method removeFilter
  1138. * @private
  1139. */
  1140. PIXI.DisplayObject.prototype.removeFilter = function(data)
  1141. {
  1142. //if(!this.filter)return;
  1143. //this.filter = false;
  1144. console.log("YUOIO")
  1145. // modify the list..
  1146. var startBlock = data.start;
  1147. var nextObject = startBlock._iNext;
  1148. var previousObject = startBlock._iPrev;
  1149. if(nextObject)nextObject._iPrev = previousObject;
  1150. if(previousObject)previousObject._iNext = nextObject;
  1151. this.first = startBlock._iNext;
  1152. // remove the end filter
  1153. var lastBlock = data.end;
  1154. var nextObject = lastBlock._iNext;
  1155. var previousObject = lastBlock._iPrev;
  1156. if(nextObject)nextObject._iPrev = previousObject;
  1157. previousObject._iNext = nextObject;
  1158. // this is always true too!
  1159. var tempLast = lastBlock._iPrev;
  1160. // need to make sure the parents last is updated too
  1161. var updateLast = this;
  1162. while(updateLast.last == lastBlock)
  1163. {
  1164. updateLast.last = tempLast;
  1165. updateLast = updateLast.parent;
  1166. if(!updateLast)break;
  1167. }
  1168. // if webGL...
  1169. if(this.__renderGroup)
  1170. {
  1171. this.__renderGroup.removeFilterBlocks(startBlock, lastBlock);
  1172. }
  1173. }
  1174. /*
  1175. * Updates the object transform for rendering
  1176. *
  1177. * @method updateTransform
  1178. * @private
  1179. */
  1180. PIXI.DisplayObject.prototype.updateTransform = function()
  1181. {
  1182. // TODO OPTIMIZE THIS!! with dirty
  1183. if(this.rotation !== this.rotationCache)
  1184. {
  1185. this.rotationCache = this.rotation;
  1186. this._sr = Math.sin(this.rotation);
  1187. this._cr = Math.cos(this.rotation);
  1188. }
  1189. var localTransform = this.localTransform;
  1190. var parentTransform = this.parent.worldTransform;
  1191. var worldTransform = this.worldTransform;
  1192. //console.log(localTransform)
  1193. localTransform[0] = this._cr * this.scale.x;
  1194. localTransform[1] = -this._sr * this.scale.y
  1195. localTransform[3] = this._sr * this.scale.x;
  1196. localTransform[4] = this._cr * this.scale.y;
  1197. // TODO --> do we even need a local matrix???
  1198. var px = this.pivot.x;
  1199. var py = this.pivot.y;
  1200. // Cache the matrix values (makes for huge speed increases!)
  1201. var a00 = localTransform[0], a01 = localTransform[1], a02 = this.position.x - localTransform[0] * px - py * localTransform[1],
  1202. a10 = localTransform[3], a11 = localTransform[4], a12 = this.position.y - localTransform[4] * py - px * localTransform[3],
  1203. b00 = parentTransform[0], b01 = parentTransform[1], b02 = parentTransform[2],
  1204. b10 = parentTransform[3], b11 = parentTransform[4], b12 = parentTransform[5];
  1205. localTransform[2] = a02
  1206. localTransform[5] = a12
  1207. worldTransform[0] = b00 * a00 + b01 * a10;
  1208. worldTransform[1] = b00 * a01 + b01 * a11;
  1209. worldTransform[2] = b00 * a02 + b01 * a12 + b02;
  1210. worldTransform[3] = b10 * a00 + b11 * a10;
  1211. worldTransform[4] = b10 * a01 + b11 * a11;
  1212. worldTransform[5] = b10 * a02 + b11 * a12 + b12;
  1213. // because we are using affine transformation, we can optimise the matrix concatenation process.. wooo!
  1214. // mat3.multiply(this.localTransform, this.parent.worldTransform, this.worldTransform);
  1215. this.worldAlpha = this.alpha * this.parent.worldAlpha;
  1216. this.vcount = PIXI.visibleCount;
  1217. }
  1218. PIXI.visibleCount = 0;
  1219. /**
  1220. * @author Mat Groves http://matgroves.com/ @Doormat23
  1221. */
  1222. /**
  1223. * A DisplayObjectContainer represents a collection of display objects.
  1224. * It is the base class of all display objects that act as a container for other objects.
  1225. *
  1226. * @class DisplayObjectContainer
  1227. * @extends DisplayObject
  1228. * @constructor
  1229. */
  1230. PIXI.DisplayObjectContainer = function()
  1231. {
  1232. PIXI.DisplayObject.call( this );
  1233. /**
  1234. * [read-only] The of children of this container.
  1235. *
  1236. * @property children
  1237. * @type Array<DisplayObject>
  1238. * @readOnly
  1239. */
  1240. this.children = [];
  1241. }
  1242. // constructor
  1243. PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype );
  1244. PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer;
  1245. /**
  1246. * Adds a child to the container.
  1247. *
  1248. * @method addChild
  1249. * @param child {DisplayObject} The DisplayObject to add to the container
  1250. */
  1251. PIXI.DisplayObjectContainer.prototype.addChild = function(child)
  1252. {
  1253. if(child.parent != undefined)
  1254. {
  1255. //// COULD BE THIS???
  1256. child.parent.removeChild(child);
  1257. // return;
  1258. }
  1259. child.parent = this;
  1260. this.children.push(child);
  1261. // update the stage refference..
  1262. if(this.stage)
  1263. {
  1264. var tmpChild = child;
  1265. do
  1266. {
  1267. if(tmpChild.interactive)this.stage.dirty = true;
  1268. tmpChild.stage = this.stage;
  1269. tmpChild = tmpChild._iNext;
  1270. }
  1271. while(tmpChild)
  1272. }
  1273. // LINKED LIST //
  1274. // modify the list..
  1275. var childFirst = child.first
  1276. var childLast = child.last;
  1277. var nextObject;
  1278. var previousObject;
  1279. // this could be wrong if there is a filter??
  1280. if(this._filters || this._mask)
  1281. {
  1282. previousObject = this.last._iPrev;
  1283. }
  1284. else
  1285. {
  1286. previousObject = this.last;
  1287. }
  1288. nextObject = previousObject._iNext;
  1289. // always true in this case
  1290. // need to make sure the parents last is updated too
  1291. var updateLast = this;
  1292. var prevLast = previousObject;
  1293. while(updateLast)
  1294. {
  1295. if(updateLast.last == prevLast)
  1296. {
  1297. updateLast.last = child.last;
  1298. }
  1299. updateLast = updateLast.parent;
  1300. }
  1301. if(nextObject)
  1302. {
  1303. nextObject._iPrev = childLast;
  1304. childLast._iNext = nextObject;
  1305. }
  1306. childFirst._iPrev = previousObject;
  1307. previousObject._iNext = childFirst;
  1308. // need to remove any render groups..
  1309. if(this.__renderGroup)
  1310. {
  1311. // being used by a renderTexture.. if it exists then it must be from a render texture;
  1312. if(child.__renderGroup)child.__renderGroup.removeDisplayObjectAndChildren(child);
  1313. // add them to the new render group..
  1314. this.__renderGroup.addDisplayObjectAndChildren(child);
  1315. }
  1316. }
  1317. /**
  1318. * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
  1319. *
  1320. * @method addChildAt
  1321. * @param child {DisplayObject} The child to add
  1322. * @param index {Number} The index to place the child in
  1323. */
  1324. PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index)
  1325. {
  1326. if(index >= 0 && index <= this.children.length)
  1327. {
  1328. if(child.parent != undefined)
  1329. {
  1330. child.parent.removeChild(child);
  1331. }
  1332. child.parent = this;
  1333. if(this.stage)
  1334. {
  1335. var tmpChild = child;
  1336. do
  1337. {
  1338. if(tmpChild.interactive)this.stage.dirty = true;
  1339. tmpChild.stage = this.stage;
  1340. tmpChild = tmpChild._iNext;
  1341. }
  1342. while(tmpChild)
  1343. }
  1344. // modify the list..
  1345. var childFirst = child.first;
  1346. var childLast = child.last;
  1347. var nextObject;
  1348. var previousObject;
  1349. if(index == this.children.length)
  1350. {
  1351. previousObject = this.last;
  1352. var updateLast = this;
  1353. var prevLast = this.last;
  1354. while(updateLast)
  1355. {
  1356. if(updateLast.last == prevLast)
  1357. {
  1358. updateLast.last = child.last;
  1359. }
  1360. updateLast = updateLast.parent;
  1361. }
  1362. }
  1363. else if(index === 0)
  1364. {
  1365. previousObject = this;
  1366. }
  1367. else
  1368. {
  1369. previousObject = this.children[index-1].last;
  1370. }
  1371. nextObject = previousObject._iNext;
  1372. // always true in this case
  1373. if(nextObject)
  1374. {
  1375. nextObject._iPrev = childLast;
  1376. childLast._iNext = nextObject;
  1377. }
  1378. childFirst._iPrev = previousObject;
  1379. previousObject._iNext = childFirst;
  1380. this.children.splice(index, 0, child);
  1381. // need to remove any render groups..
  1382. if(this.__renderGroup)
  1383. {
  1384. // being used by a renderTexture.. if it exists then it must be from a render texture;
  1385. if(child.__renderGroup)child.__renderGroup.removeDisplayObjectAndChildren(child);
  1386. // add them to the new render group..
  1387. this.__renderGroup.addDisplayObjectAndChildren(child);
  1388. }
  1389. }
  1390. else
  1391. {
  1392. throw new Error(child + " The index "+ index +" supplied is out of bounds " + this.children.length);
  1393. }
  1394. }
  1395. /**
  1396. * [NYI] Swaps the depth of 2 displayObjects
  1397. *
  1398. * @method swapChildren
  1399. * @param child {DisplayObject}
  1400. * @param child2 {DisplayObject}
  1401. * @private
  1402. */
  1403. PIXI.DisplayObjectContainer.prototype.swapChildren = function(child, child2)
  1404. {
  1405. /*
  1406. * this funtion needs to be recoded..
  1407. * can be done a lot faster..
  1408. */
  1409. return;
  1410. // need to fix this function :/
  1411. /*
  1412. // TODO I already know this??
  1413. var index = this.children.indexOf( child );
  1414. var index2 = this.children.indexOf( child2 );
  1415. if ( index !== -1 && index2 !== -1 )
  1416. {
  1417. // cool
  1418. /*
  1419. if(this.stage)
  1420. {
  1421. // this is to satisfy the webGL batching..
  1422. // TODO sure there is a nicer way to achieve this!
  1423. this.stage.__removeChild(child);
  1424. this.stage.__removeChild(child2);
  1425. this.stage.__addChild(child);
  1426. this.stage.__addChild(child2);
  1427. }
  1428. // swap the positions..
  1429. this.children[index] = child2;
  1430. this.children[index2] = child;
  1431. }
  1432. else
  1433. {
  1434. throw new Error(child + " Both the supplied DisplayObjects must be a child of the caller " + this);
  1435. }*/
  1436. }
  1437. /**
  1438. * Returns the Child at the specified index
  1439. *
  1440. * @method getChildAt
  1441. * @param index {Number} The index to get the child from
  1442. */
  1443. PIXI.DisplayObjectContainer.prototype.getChildAt = function(index)
  1444. {
  1445. if(index >= 0 && index < this.children.length)
  1446. {
  1447. return this.children[index];
  1448. }
  1449. else
  1450. {
  1451. throw new Error(child + " Both the supplied DisplayObjects must be a child of the caller " + this);
  1452. }
  1453. }
  1454. /**
  1455. * Removes a child from the container.
  1456. *
  1457. * @method removeChild
  1458. * @param child {DisplayObject} The DisplayObject to remove
  1459. */
  1460. PIXI.DisplayObjectContainer.prototype.removeChild = function(child)
  1461. {
  1462. var index = this.children.indexOf( child );
  1463. if ( index !== -1 )
  1464. {
  1465. // unlink //
  1466. // modify the list..
  1467. var childFirst = child.first;
  1468. var childLast = child.last;
  1469. var nextObject = childLast._iNext;
  1470. var previousObject = childFirst._iPrev;
  1471. if(nextObject)nextObject._iPrev = previousObject;
  1472. previousObject._iNext = nextObject;
  1473. if(this.last == childLast)
  1474. {
  1475. var tempLast = childFirst._iPrev;
  1476. // need to make sure the parents last is updated too
  1477. var updateLast = this;
  1478. while(updateLast.last == childLast.last)
  1479. {
  1480. updateLast.last = tempLast;
  1481. updateLast = updateLast.parent;
  1482. if(!updateLast)break;
  1483. }
  1484. }
  1485. childLast._iNext = null;
  1486. childFirst._iPrev = null;
  1487. // update the stage reference..
  1488. if(this.stage)
  1489. {
  1490. var tmpChild = child;
  1491. do
  1492. {
  1493. if(tmpChild.interactive)this.stage.dirty = true;
  1494. tmpChild.stage = null;
  1495. tmpChild = tmpChild._iNext;
  1496. }
  1497. while(tmpChild)
  1498. }
  1499. // webGL trim
  1500. if(child.__renderGroup)
  1501. {
  1502. child.__renderGroup.removeDisplayObjectAndChildren(child);
  1503. }
  1504. child.parent = undefined;
  1505. this.children.splice( index, 1 );
  1506. }
  1507. else
  1508. {
  1509. throw new Error(child + " The supplied DisplayObject must be a child of the caller " + this);
  1510. }
  1511. }
  1512. /*
  1513. * Updates the container's children's transform for rendering
  1514. *
  1515. * @method updateTransform
  1516. * @private
  1517. */
  1518. PIXI.DisplayObjectContainer.prototype.updateTransform = function()
  1519. {
  1520. if(!this.visible)return;
  1521. PIXI.DisplayObject.prototype.updateTransform.call( this );
  1522. for(var i=0,j=this.children.length; i<j; i++)
  1523. {
  1524. this.children[i].updateTransform();
  1525. }
  1526. }
  1527. /**
  1528. * @author Mat Groves http://matgroves.com/ @Doormat23
  1529. */
  1530. PIXI.blendModes = {};
  1531. PIXI.blendModes.NORMAL = 0;
  1532. PIXI.blendModes.SCREEN = 1;
  1533. /**
  1534. * The SPrite object is the base for all textured objects that are rendered to the screen
  1535. *
  1536. * @class Sprite
  1537. * @extends DisplayObjectContainer
  1538. * @constructor
  1539. * @param texture {Texture} The texture for this sprite
  1540. * @type String
  1541. */
  1542. PIXI.Sprite = function(texture)
  1543. {
  1544. PIXI.DisplayObjectContainer.call( this );
  1545. /**
  1546. * The anchor sets the origin point of the texture.
  1547. * The default is 0,0 this means the textures origin is the top left
  1548. * Setting than anchor to 0.5,0.5 means the textures origin is centered
  1549. * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right
  1550. *
  1551. * @property anchor
  1552. * @type Point
  1553. */
  1554. this.anchor = new PIXI.Point();
  1555. /**
  1556. * The texture that the sprite is using
  1557. *
  1558. * @property texture
  1559. * @type Texture
  1560. */
  1561. this.texture = texture;
  1562. /**
  1563. * The blend mode of sprite.
  1564. * currently supports PIXI.blendModes.NORMAL and PIXI.blendModes.SCREEN
  1565. *
  1566. * @property blendMode
  1567. * @type Number
  1568. */
  1569. this.blendMode = PIXI.blendModes.NORMAL;
  1570. /**
  1571. * The width of the sprite (this is initially set by the texture)
  1572. *
  1573. * @property _width
  1574. * @type Number
  1575. * @private
  1576. */
  1577. this._width = 0;
  1578. /**
  1579. * The height of the sprite (this is initially set by the texture)
  1580. *
  1581. * @property _height
  1582. * @type Number
  1583. * @private
  1584. */
  1585. this._height = 0;
  1586. if(texture.baseTexture.hasLoaded)
  1587. {
  1588. this.updateFrame = true;
  1589. }
  1590. else
  1591. {
  1592. this.onTextureUpdateBind = this.onTextureUpdate.bind(this);
  1593. this.texture.addEventListener( 'update', this.onTextureUpdateBind );
  1594. }
  1595. this.renderable = true;
  1596. }
  1597. // constructor
  1598. PIXI.Sprite.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
  1599. PIXI.Sprite.prototype.constructor = PIXI.Sprite;
  1600. /**
  1601. * The width of the sprite, setting this will actually modify the scale to acheive the value set
  1602. *
  1603. * @property width
  1604. * @type Number
  1605. */
  1606. Object.defineProperty(PIXI.Sprite.prototype, 'width', {
  1607. get: function() {
  1608. return this.scale.x * this.texture.frame.width;
  1609. },
  1610. set: function(value) {
  1611. this.scale.x = value / this.texture.frame.width
  1612. this._width = value;
  1613. }
  1614. });
  1615. /**
  1616. * The height of the sprite, setting this will actually modify the scale to acheive the value set
  1617. *
  1618. * @property height
  1619. * @type Number
  1620. */
  1621. Object.defineProperty(PIXI.Sprite.prototype, 'height', {
  1622. get: function() {
  1623. return this.scale.y * this.texture.frame.height;
  1624. },
  1625. set: function(value) {
  1626. this.scale.y = value / this.texture.frame.height
  1627. this._height = value;
  1628. }
  1629. });
  1630. /**
  1631. * Sets the texture of the sprite
  1632. *
  1633. * @method setTexture
  1634. * @param texture {Texture} The PIXI texture that is displayed by the sprite
  1635. */
  1636. PIXI.Sprite.prototype.setTexture = function(texture)
  1637. {
  1638. // stop current texture;
  1639. if(this.texture.baseTexture != texture.baseTexture)
  1640. {
  1641. this.textureChange = true;
  1642. this.texture = texture;
  1643. if(this.__renderGroup)
  1644. {
  1645. this.__renderGroup.updateTexture(this);
  1646. }
  1647. }
  1648. else
  1649. {
  1650. this.texture = texture;
  1651. }
  1652. this.updateFrame = true;
  1653. }
  1654. /**
  1655. * When the texture is updated, this event will fire to update the scale and frame
  1656. *
  1657. * @method onTextureUpdate
  1658. * @param event
  1659. * @private
  1660. */
  1661. PIXI.Sprite.prototype.onTextureUpdate = function(event)
  1662. {
  1663. //this.texture.removeEventListener( 'update', this.onTextureUpdateBind );
  1664. // so if _width is 0 then width was not set..
  1665. if(this._width)this.scale.x = this._width / this.texture.frame.width;
  1666. if(this._height)this.scale.y = this._height / this.texture.frame.height;
  1667. this.updateFrame = true;
  1668. }
  1669. // some helper functions..
  1670. /**
  1671. *
  1672. * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
  1673. * The frame ids are created when a Texture packer file has been loaded
  1674. *
  1675. * @method fromFrame
  1676. * @static
  1677. * @param frameId {String} The frame Id of the texture in the cache
  1678. * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId
  1679. */
  1680. PIXI.Sprite.fromFrame = function(frameId)
  1681. {
  1682. var texture = PIXI.TextureCache[frameId];
  1683. if(!texture)throw new Error("The frameId '"+ frameId +"' does not exist in the texture cache" + this);
  1684. return new PIXI.Sprite(texture);
  1685. }
  1686. /**
  1687. *
  1688. * Helper function that creates a sprite that will contain a texture based on an image url
  1689. * If the image is not in the texture cache it will be loaded
  1690. *
  1691. * @method fromImage
  1692. * @static
  1693. * @param imageId {String} The image url of the texture
  1694. * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id
  1695. */
  1696. PIXI.Sprite.fromImage = function(imageId)
  1697. {
  1698. var texture = PIXI.Texture.fromImage(imageId);
  1699. return new PIXI.Sprite(texture);
  1700. }
  1701. /**
  1702. * @author Mat Groves http://matgroves.com/ @Doormat23
  1703. */
  1704. /**
  1705. * A Stage represents the root of the display tree. Everything connected to the stage is rendered
  1706. *
  1707. * @class Stage
  1708. * @extends DisplayObjectContainer
  1709. * @constructor
  1710. * @param backgroundColor {Number} the background color of the stage, easiest way to pass this in is in hex format
  1711. * like: 0xFFFFFF for white
  1712. */
  1713. PIXI.Stage = function(backgroundColor)
  1714. {
  1715. PIXI.DisplayObjectContainer.call( this );
  1716. /**
  1717. * [read-only] Current transform of the object based on world (parent) factors
  1718. *
  1719. * @property worldTransform
  1720. * @type Mat3
  1721. * @readOnly
  1722. * @private
  1723. */
  1724. this.worldTransform = PIXI.mat3.create();
  1725. /**
  1726. * Whether or not the stage is interactive
  1727. *
  1728. * @property interactive
  1729. * @type Boolean
  1730. */
  1731. this.interactive = true;
  1732. /**
  1733. * The interaction manage for this stage, manages all interactive activity on the stage
  1734. *
  1735. * @property interactive
  1736. * @type InteractionManager
  1737. */
  1738. this.interactionManager = new PIXI.InteractionManager(this);
  1739. /**
  1740. * Whether the stage is dirty and needs to have interactions updated
  1741. *
  1742. * @property dirty
  1743. * @type Boolean
  1744. * @private
  1745. */
  1746. this.dirty = true;
  1747. this.__childrenAdded = [];
  1748. this.__childrenRemoved = [];
  1749. //the stage is it's own stage
  1750. this.stage = this;
  1751. //optimize hit detection a bit
  1752. this.stage.hitArea = new PIXI.Rectangle(0,0,100000, 100000);
  1753. this.setBackgroundColor(backgroundColor);
  1754. this.worldVisible = true;
  1755. }
  1756. // constructor
  1757. PIXI.Stage.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
  1758. PIXI.Stage.prototype.constructor = PIXI.Stage;
  1759. /**
  1760. * Sets another DOM element which can receive mouse/touch interactions instead of the default Canvas element.
  1761. * This is useful for when you have other DOM elements ontop of the Canvas element.
  1762. *
  1763. * @method setInteractionDelegate
  1764. * @param domElement {DOMElement} This new domElement which will receive mouse/touch events
  1765. */
  1766. PIXI.Stage.prototype.setInteractionDelegate = function(domElement)
  1767. {
  1768. this.interactionManager.setTargetDomElement( domElement );
  1769. }
  1770. /*
  1771. * Updates the object transform for rendering
  1772. *
  1773. * @method updateTransform
  1774. * @private
  1775. */
  1776. PIXI.Stage.prototype.updateTransform = function()
  1777. {
  1778. this.worldAlpha = 1;
  1779. this.vcount = PIXI.visibleCount;
  1780. for(var i=0,j=this.children.length; i<j; i++)
  1781. {
  1782. this.children[i].updateTransform();
  1783. }
  1784. if(this.dirty)
  1785. {
  1786. this.dirty = false;
  1787. // update interactive!
  1788. this.interactionManager.dirty = true;
  1789. }
  1790. if(this.interactive)this.interactionManager.update();
  1791. }
  1792. /**
  1793. * Sets the background color for the stage
  1794. *
  1795. * @method setBackgroundColor
  1796. * @param backgroundColor {Number} the color of the background, easiest way to pass this in is in hex format
  1797. * like: 0xFFFFFF for white
  1798. */
  1799. PIXI.Stage.prototype.setBackgroundColor = function(backgroundColor)
  1800. {
  1801. this.backgroundColor = backgroundColor || 0x000000;
  1802. this.backgroundColorSplit = HEXtoRGB(this.backgroundColor);
  1803. var hex = this.backgroundColor.toString(16);
  1804. hex = "000000".substr(0, 6 - hex.length) + hex;
  1805. this.backgroundColorString = "#" + hex;
  1806. }
  1807. /**
  1808. * This will return the point containing global coords of the mouse.
  1809. *
  1810. * @method getMousePosition
  1811. * @return {Point} The point containing the coords of the global InteractionData position.
  1812. */
  1813. PIXI.Stage.prototype.getMousePosition = function()
  1814. {
  1815. return this.interactionManager.mouse.global;
  1816. }
  1817. /**
  1818. * @author Mat Groves http://matgroves.com/ @Doormat23
  1819. */
  1820. /**
  1821. * This object is one that will allow you to specify custom rendering functions based on render type
  1822. *
  1823. * @class CustomRenderable
  1824. * @extends DisplayObject
  1825. * @constructor
  1826. */
  1827. PIXI.CustomRenderable = function()
  1828. {
  1829. PIXI.DisplayObject.call( this );
  1830. this.renderable = true;
  1831. }
  1832. // constructor
  1833. PIXI.CustomRenderable.prototype = Object.create( PIXI.DisplayObject.prototype );
  1834. PIXI.CustomRenderable.prototype.constructor = PIXI.CustomRenderable;
  1835. /**
  1836. * If this object is being rendered by a CanvasRenderer it will call this callback
  1837. *
  1838. * @method renderCanvas
  1839. * @param renderer {CanvasRenderer} The renderer instance
  1840. */
  1841. PIXI.CustomRenderable.prototype.renderCanvas = function(renderer)
  1842. {
  1843. // override!
  1844. }
  1845. /**
  1846. * If this object is being rendered by a WebGLRenderer it will call this callback to initialize
  1847. *
  1848. * @method initWebGL
  1849. * @param renderer {WebGLRenderer} The renderer instance
  1850. */
  1851. PIXI.CustomRenderable.prototype.initWebGL = function(renderer)
  1852. {
  1853. // override!
  1854. }
  1855. /**
  1856. * If this object is being rendered by a WebGLRenderer it will call this callback
  1857. *
  1858. * @method renderWebGL
  1859. * @param renderer {WebGLRenderer} The renderer instance
  1860. */
  1861. PIXI.CustomRenderable.prototype.renderWebGL = function(renderGroup, projectionMatrix)
  1862. {
  1863. // not sure if both needed? but ya have for now!
  1864. // override!
  1865. }
  1866. /**
  1867. * @author Mat Groves http://matgroves.com/
  1868. */
  1869. PIXI.Strip = function(texture, width, height)
  1870. {
  1871. PIXI.DisplayObjectContainer.call( this );
  1872. this.texture = texture;
  1873. this.blendMode = PIXI.blendModes.NORMAL;
  1874. try
  1875. {
  1876. this.uvs = new Float32Array([0, 1,
  1877. 1, 1,
  1878. 1, 0, 0,1]);
  1879. this.verticies = new Float32Array([0, 0,
  1880. 0,0,
  1881. 0,0, 0,
  1882. 0, 0]);
  1883. this.colors = new Float32Array([1, 1, 1, 1]);
  1884. this.indices = new Uint16Array([0, 1, 2, 3]);
  1885. }
  1886. catch(error)
  1887. {
  1888. this.uvs = [0, 1,
  1889. 1, 1,
  1890. 1, 0, 0,1];
  1891. this.verticies = [0, 0,
  1892. 0,0,
  1893. 0,0, 0,
  1894. 0, 0];
  1895. this.colors = [1, 1, 1, 1];
  1896. this.indices = [0, 1, 2, 3];
  1897. }
  1898. /*
  1899. this.uvs = new Float32Array()
  1900. this.verticies = new Float32Array()
  1901. this.colors = new Float32Array()
  1902. this.indices = new Uint16Array()
  1903. */
  1904. this.width = width;
  1905. this.height = height;
  1906. // load the texture!
  1907. if(texture.baseTexture.hasLoaded)
  1908. {
  1909. this.width = this.texture.frame.width;
  1910. this.height = this.texture.frame.height;
  1911. this.updateFrame = true;
  1912. }
  1913. else
  1914. {
  1915. this.onTextureUpdateBind = this.onTextureUpdate.bind(this);
  1916. this.texture.addEventListener( 'update', this.onTextureUpdateBind );
  1917. }
  1918. this.renderable = true;
  1919. }
  1920. // constructor
  1921. PIXI.Strip.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
  1922. PIXI.Strip.prototype.constructor = PIXI.Strip;
  1923. PIXI.Strip.prototype.setTexture = function(texture)
  1924. {
  1925. //TODO SET THE TEXTURES
  1926. //TODO VISIBILITY
  1927. // stop current texture
  1928. this.texture = texture;
  1929. this.width = texture.frame.width;
  1930. this.height = texture.frame.height;
  1931. this.updateFrame = true;
  1932. }
  1933. PIXI.Strip.prototype.onTextureUpdate = function(event)
  1934. {
  1935. this.updateFrame = true;
  1936. }
  1937. // some helper functions..
  1938. /**
  1939. * @author Mat Groves http://matgroves.com/
  1940. */
  1941. PIXI.Rope = function(texture, points)
  1942. {
  1943. PIXI.Strip.call( this, texture );
  1944. this.points = points;
  1945. try
  1946. {
  1947. this.verticies = new Float32Array( points.length * 4);
  1948. this.uvs = new Float32Array( points.length * 4);
  1949. this.colors = new Float32Array( points.length * 2);
  1950. this.indices = new Uint16Array( points.length * 2);
  1951. }
  1952. catch(error)
  1953. {
  1954. this.verticies = verticies
  1955. this.uvs = uvs
  1956. this.colors = colors
  1957. this.indices = indices
  1958. }
  1959. this.refresh();
  1960. }
  1961. // constructor
  1962. PIXI.Rope.prototype = Object.create( PIXI.Strip.prototype );
  1963. PIXI.Rope.prototype.constructor = PIXI.Rope;
  1964. PIXI.Rope.prototype.refresh = function()
  1965. {
  1966. var points = this.points;
  1967. if(points.length < 1)return;
  1968. var uvs = this.uvs
  1969. var indices = this.indices;
  1970. var colors = this.colors;
  1971. var lastPoint = points[0];
  1972. var nextPoint;
  1973. var perp = {x:0, y:0};
  1974. var point = points[0];
  1975. this.count-=0.2;
  1976. uvs[0] = 0
  1977. uvs[1] = 1
  1978. uvs[2] = 0
  1979. uvs[3] = 1
  1980. colors[0] = 1;
  1981. colors[1] = 1;
  1982. indices[0] = 0;
  1983. indices[1] = 1;
  1984. var total = points.length;
  1985. for (var i = 1; i < total; i++)
  1986. {
  1987. var point = points[i];
  1988. var index = i * 4;
  1989. // time to do some smart drawing!
  1990. var amount = i/(total-1)
  1991. if(i%2)
  1992. {
  1993. uvs[index] = amount;
  1994. uvs[index+1] = 0;
  1995. uvs[index+2] = amount
  1996. uvs[index+3] = 1
  1997. }
  1998. else
  1999. {
  2000. uvs[index] = amount
  2001. uvs[index+1] = 0
  2002. uvs[index+2] = amount
  2003. uvs[index+3] = 1
  2004. }
  2005. index = i * 2;
  2006. colors[index] = 1;
  2007. colors[index+1] = 1;
  2008. index = i * 2;
  2009. indices[index] = index;
  2010. indices[index + 1] = index + 1;
  2011. lastPoint = point;
  2012. }
  2013. }
  2014. PIXI.Rope.prototype.updateTransform = function()
  2015. {
  2016. var points = this.points;
  2017. if(points.length < 1)return;
  2018. var verticies = this.verticies
  2019. var lastPoint = points[0];
  2020. var nextPoint;
  2021. var perp = {x:0, y:0};
  2022. var point = points[0];
  2023. this.count-=0.2;
  2024. verticies[0] = point.x + perp.x
  2025. verticies[1] = point.y + perp.y //+ 200
  2026. verticies[2] = point.x - perp.x
  2027. verticies[3] = point.y - perp.y//+200
  2028. // time to do some smart drawing!
  2029. var total = points.length;
  2030. for (var i = 1; i < total; i++)
  2031. {
  2032. var point = points[i];
  2033. var index = i * 4;
  2034. if(i < points.length-1)
  2035. {
  2036. nextPoint = points[i+1];
  2037. }
  2038. else
  2039. {
  2040. nextPoint = point
  2041. }
  2042. perp.y = -(nextPoint.x - lastPoint.x);
  2043. perp.x = nextPoint.y - lastPoint.y;
  2044. var ratio = (1 - (i / (total-1))) * 10;
  2045. if(ratio > 1)ratio = 1;
  2046. var perpLength = Math.sqrt(perp.x * perp.x + perp.y * perp.y);
  2047. var num = this.texture.height/2//(20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio;
  2048. perp.x /= perpLength;
  2049. perp.y /= perpLength;
  2050. perp.x *= num;
  2051. perp.y *= num;
  2052. verticies[index] = point.x + perp.x
  2053. verticies[index+1] = point.y + perp.y
  2054. verticies[index+2] = point.x - perp.x
  2055. verticies[index+3] = point.y - perp.y
  2056. lastPoint = point;
  2057. }
  2058. PIXI.DisplayObjectContainer.prototype.updateTransform.call( this );
  2059. }
  2060. PIXI.Rope.prototype.setTexture = function(texture)
  2061. {
  2062. // stop current texture
  2063. this.texture = texture;
  2064. this.updateFrame = true;
  2065. }
  2066. /**
  2067. * @author Mat Groves http://matgroves.com/
  2068. */
  2069. /**
  2070. * A tiling sprite is a fast way of rendering a tiling image
  2071. *
  2072. * @class TilingSprite
  2073. * @extends DisplayObjectContainer
  2074. * @constructor
  2075. * @param texture {Texture} the texture of the tiling sprite
  2076. * @param width {Number} the width of the tiling sprite
  2077. * @param height {Number} the height of the tiling sprite
  2078. */
  2079. PIXI.TilingSprite = function(texture, width, height)
  2080. {
  2081. PIXI.DisplayObjectContainer.call( this );
  2082. /**
  2083. * The texture that the sprite is using
  2084. *
  2085. * @property texture
  2086. * @type Texture
  2087. */
  2088. this.texture = texture;
  2089. /**
  2090. * The width of the tiling sprite
  2091. *
  2092. * @property width
  2093. * @type Number
  2094. */
  2095. this.width = width;
  2096. /**
  2097. * The height of the tiling sprite
  2098. *
  2099. * @property height
  2100. * @type Number
  2101. */
  2102. this.height = height;
  2103. /**
  2104. * The scaling of the image that is being tiled
  2105. *
  2106. * @property tileScale
  2107. * @type Point
  2108. */
  2109. this.tileScale = new PIXI.Point(1,1);
  2110. /**
  2111. * The offset position of the image that is being tiled
  2112. *
  2113. * @property tilePosition
  2114. * @type Point
  2115. */
  2116. this.tilePosition = new PIXI.Point(0,0);
  2117. this.renderable = true;
  2118. this.blendMode = PIXI.blendModes.NORMAL
  2119. }
  2120. // constructor
  2121. PIXI.TilingSprite.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
  2122. PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite;
  2123. /**
  2124. * Sets the texture of the tiling sprite
  2125. *
  2126. * @method setTexture
  2127. * @param texture {Texture} The PIXI texture that is displayed by the sprite
  2128. */
  2129. PIXI.TilingSprite.prototype.setTexture = function(texture)
  2130. {
  2131. //TODO SET THE TEXTURES
  2132. //TODO VISIBILITY
  2133. // stop current texture
  2134. this.texture = texture;
  2135. this.updateFrame = true;
  2136. }
  2137. /**
  2138. * When the texture is updated, this event will fire to update the frame
  2139. *
  2140. * @method onTextureUpdate
  2141. * @param event
  2142. * @private
  2143. */
  2144. PIXI.TilingSprite.prototype.onTextureUpdate = function(event)
  2145. {
  2146. this.updateFrame = true;
  2147. }
  2148. /**
  2149. * @author Mat Groves http://matgroves.com/ @Doormat23
  2150. */
  2151. /**
  2152. * This is the base class for creating a pixi.js filter. Currently only webGL supports filters.
  2153. * If you want to make a custom filter this should be your base class.
  2154. * @class AbstractFilter
  2155. * @constructor
  2156. * @param fragmentSrc
  2157. * @param uniforms
  2158. */
  2159. PIXI.AbstractFilter = function(fragmentSrc, uniforms)
  2160. {
  2161. /**
  2162. * An array of passes - some filters contain a few steps this array simply stores the steps in a liniear fashion.
  2163. * For example the blur filter has two passes blurX and blurY.
  2164. * @property passes
  2165. * @type Array an array of filter objects
  2166. * @private
  2167. */
  2168. this.passes = [this];
  2169. this.dirty = true;
  2170. this.padding = 0;
  2171. /**
  2172. @property uniforms
  2173. @private
  2174. */
  2175. this.uniforms = uniforms || {};
  2176. this.fragmentSrc = fragmentSrc || [];
  2177. }
  2178. /**
  2179. * @author Mat Groves http://matgroves.com/ @Doormat23
  2180. */
  2181. PIXI.FilterBlock = function()
  2182. {
  2183. this.visible = true;
  2184. this.renderable = true;
  2185. }
  2186. /**
  2187. * @author Mat Groves http://matgroves.com/ @Doormat23
  2188. */
  2189. /**
  2190. * The Graphics class contains a set of methods that you can use to create primitive shapes and lines.
  2191. * It is important to know that with the webGL renderer only simple polys can be filled at this stage
  2192. * Complex polys will not be filled. Heres an example of a complex poly: http://www.goodboydigital.com/wp-content/uploads/2013/06/complexPolygon.png
  2193. *
  2194. * @class Graphics
  2195. * @extends DisplayObjectContainer
  2196. * @constructor
  2197. */
  2198. PIXI.Graphics = function()
  2199. {
  2200. PIXI.DisplayObjectContainer.call( this );
  2201. this.renderable = true;
  2202. /**
  2203. * The alpha of the fill of this graphics object
  2204. *
  2205. * @property fillAlpha
  2206. * @type Number
  2207. */
  2208. this.fillAlpha = 1;
  2209. /**
  2210. * The width of any lines drawn
  2211. *
  2212. * @property lineWidth
  2213. * @type Number
  2214. */
  2215. this.lineWidth = 0;
  2216. /**
  2217. * The color of any lines drawn
  2218. *
  2219. * @property lineColor
  2220. * @type String
  2221. */
  2222. this.lineColor = "black";
  2223. /**
  2224. * Graphics data
  2225. *
  2226. * @property graphicsData
  2227. * @type Array
  2228. * @private
  2229. */
  2230. this.graphicsData = [];
  2231. /**
  2232. * Current path
  2233. *
  2234. * @property currentPath
  2235. * @type Object
  2236. * @private
  2237. */
  2238. this.currentPath = {points:[]};
  2239. }
  2240. // constructor
  2241. PIXI.Graphics.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
  2242. PIXI.Graphics.prototype.constructor = PIXI.Graphics;
  2243. /**
  2244. * Specifies a line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.
  2245. *
  2246. * @method lineStyle
  2247. * @param lineWidth {Number} width of the line to draw, will update the object's stored style
  2248. * @param color {Number} color of the line to draw, will update the object's stored style
  2249. * @param alpha {Number} alpha of the line to draw, will update the object's stored style
  2250. */
  2251. PIXI.Graphics.prototype.lineStyle = function(lineWidth, color, alpha)
  2252. {
  2253. if(this.currentPath.points.length === 0)this.graphicsData.pop();
  2254. this.lineWidth = lineWidth || 0;
  2255. this.lineColor = color || 0;
  2256. this.lineAlpha = (alpha == undefined) ? 1 : alpha;
  2257. this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  2258. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, points:[], type:PIXI.Graphics.POLY};
  2259. this.graphicsData.push(this.currentPath);
  2260. }
  2261. /**
  2262. * Moves the current drawing position to (x, y).
  2263. *
  2264. * @method moveTo
  2265. * @param x {Number} the X coord to move to
  2266. * @param y {Number} the Y coord to move to
  2267. */
  2268. PIXI.Graphics.prototype.moveTo = function(x, y)
  2269. {
  2270. if(this.currentPath.points.length === 0)this.graphicsData.pop();
  2271. this.currentPath = this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  2272. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, points:[], type:PIXI.Graphics.POLY};
  2273. this.currentPath.points.push(x, y);
  2274. this.graphicsData.push(this.currentPath);
  2275. }
  2276. /**
  2277. * Draws a line using the current line style from the current drawing position to (x, y);
  2278. * the current drawing position is then set to (x, y).
  2279. *
  2280. * @method lineTo
  2281. * @param x {Number} the X coord to draw to
  2282. * @param y {Number} the Y coord to draw to
  2283. */
  2284. PIXI.Graphics.prototype.lineTo = function(x, y)
  2285. {
  2286. this.currentPath.points.push(x, y);
  2287. this.dirty = true;
  2288. }
  2289. /**
  2290. * Specifies a simple one-color fill that subsequent calls to other Graphics methods
  2291. * (such as lineTo() or drawCircle()) use when drawing.
  2292. *
  2293. * @method beginFill
  2294. * @param color {uint} the color of the fill
  2295. * @param alpha {Number} the alpha
  2296. */
  2297. PIXI.Graphics.prototype.beginFill = function(color, alpha)
  2298. {
  2299. this.filling = true;
  2300. this.fillColor = color || 0;
  2301. this.fillAlpha = (alpha == undefined) ? 1 : alpha;
  2302. }
  2303. /**
  2304. * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
  2305. *
  2306. * @method endFill
  2307. */
  2308. PIXI.Graphics.prototype.endFill = function()
  2309. {
  2310. this.filling = false;
  2311. this.fillColor = null;
  2312. this.fillAlpha = 1;
  2313. }
  2314. /**
  2315. * @method drawRect
  2316. *
  2317. * @param x {Number} The X coord of the top-left of the rectangle
  2318. * @param y {Number} The Y coord of the top-left of the rectangle
  2319. * @param width {Number} The width of the rectangle
  2320. * @param height {Number} The height of the rectangle
  2321. */
  2322. PIXI.Graphics.prototype.drawRect = function( x, y, width, height )
  2323. {
  2324. if(this.currentPath.points.length === 0)this.graphicsData.pop();
  2325. this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  2326. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling,
  2327. points:[x, y, width, height], type:PIXI.Graphics.RECT};
  2328. this.graphicsData.push(this.currentPath);
  2329. this.dirty = true;
  2330. }
  2331. /**
  2332. * Draws a circle.
  2333. *
  2334. * @method drawCircle
  2335. * @param x {Number} The X coord of the center of the circle
  2336. * @param y {Number} The Y coord of the center of the circle
  2337. * @param radius {Number} The radius of the circle
  2338. */
  2339. PIXI.Graphics.prototype.drawCircle = function( x, y, radius)
  2340. {
  2341. if(this.currentPath.points.length === 0)this.graphicsData.pop();
  2342. this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  2343. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling,
  2344. points:[x, y, radius, radius], type:PIXI.Graphics.CIRC};
  2345. this.graphicsData.push(this.currentPath);
  2346. this.dirty = true;
  2347. }
  2348. /**
  2349. * Draws an elipse.
  2350. *
  2351. * @method drawElipse
  2352. * @param x {Number}
  2353. * @param y {Number}
  2354. * @param width {Number}
  2355. * @param height {Number}
  2356. */
  2357. PIXI.Graphics.prototype.drawElipse = function( x, y, width, height)
  2358. {
  2359. if(this.currentPath.points.length === 0)this.graphicsData.pop();
  2360. this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  2361. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling,
  2362. points:[x, y, width, height], type:PIXI.Graphics.ELIP};
  2363. this.graphicsData.push(this.currentPath);
  2364. this.dirty = true;
  2365. }
  2366. /**
  2367. * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
  2368. *
  2369. * @method clear
  2370. */
  2371. PIXI.Graphics.prototype.clear = function()
  2372. {
  2373. this.lineWidth = 0;
  2374. this.filling = false;
  2375. this.dirty = true;
  2376. this.clearDirty = true;
  2377. this.graphicsData = [];
  2378. this.bounds = null//new PIXI.Rectangle();
  2379. }
  2380. PIXI.Graphics.prototype.updateFilterBounds = function()
  2381. {
  2382. if(!this.bounds)
  2383. {
  2384. var minX = Infinity;
  2385. var maxX = -Infinity;
  2386. var minY = Infinity;
  2387. var maxY = -Infinity;
  2388. var points, x, y;
  2389. for (var i = 0; i < this.graphicsData.length; i++) {
  2390. var data = this.graphicsData[i];
  2391. var type = data.type;
  2392. var lineWidth = data.lineWidth;
  2393. points = data.points;
  2394. if(type === PIXI.Graphics.RECT)
  2395. {
  2396. x = points.x - lineWidth/2;
  2397. y = points.y - lineWidth/2;
  2398. var width = points.width + lineWidth;
  2399. var height = points.height + lineWidth;
  2400. minX = x < minX ? x : minX;
  2401. maxX = x + width > maxX ? x + width : maxX;
  2402. minY = y < minY ? x : minY;
  2403. maxY = y + height > maxY ? y + height : maxY;
  2404. }
  2405. else if(type === PIXI.Graphics.CIRC || type === PIXI.Graphics.ELIP)
  2406. {
  2407. x = points.x;
  2408. y = points.y;
  2409. var radius = points.radius + lineWidth/2;
  2410. minX = x - radius < minX ? x - radius : minX;
  2411. maxX = x + radius > maxX ? x + radius : maxX;
  2412. minY = y - radius < minY ? y - radius : minY;
  2413. maxY = y + radius > maxY ? y + radius : maxY;
  2414. }
  2415. else
  2416. {
  2417. // POLY
  2418. for (var j = 0; j < points.length; j+=2)
  2419. {
  2420. x = points[j];
  2421. y = points[j+1];
  2422. minX = x-lineWidth < minX ? x-lineWidth : minX;
  2423. maxX = x+lineWidth > maxX ? x+lineWidth : maxX;
  2424. minY = y-lineWidth < minY ? y-lineWidth : minY;
  2425. maxY = y+lineWidth > maxY ? y+lineWidth : maxY;
  2426. };
  2427. }
  2428. };
  2429. this.bounds = new PIXI.Rectangle(minX, minY, maxX - minX, maxY - minY);
  2430. }
  2431. // console.log(this.bounds);
  2432. }
  2433. // SOME TYPES:
  2434. PIXI.Graphics.POLY = 0;
  2435. PIXI.Graphics.RECT = 1;
  2436. PIXI.Graphics.CIRC = 2;
  2437. PIXI.Graphics.ELIP = 3;
  2438. /**
  2439. * @author Mat Groves http://matgroves.com/ @Doormat23
  2440. */
  2441. /**
  2442. * A set of functions used by the canvas renderer to draw the primitive graphics data
  2443. *
  2444. * @class CanvasGraphics
  2445. */
  2446. PIXI.CanvasGraphics = function()
  2447. {
  2448. }
  2449. /*
  2450. * Renders the graphics object
  2451. *
  2452. * @static
  2453. * @private
  2454. * @method renderGraphics
  2455. * @param graphics {Graphics}
  2456. * @param context {Context2D}
  2457. */
  2458. PIXI.CanvasGraphics.renderGraphics = function(graphics, context)
  2459. {
  2460. var worldAlpha = graphics.worldAlpha;
  2461. for (var i=0; i < graphics.graphicsData.length; i++)
  2462. {
  2463. var data = graphics.graphicsData[i];
  2464. var points = data.points;
  2465. context.strokeStyle = color = '#' + ('00000' + ( data.lineColor | 0).toString(16)).substr(-6);
  2466. context.lineWidth = data.lineWidth;
  2467. if(data.type == PIXI.Graphics.POLY)
  2468. {
  2469. context.beginPath();
  2470. context.moveTo(points[0], points[1]);
  2471. for (var j=1; j < points.length/2; j++)
  2472. {
  2473. context.lineTo(points[j * 2], points[j * 2 + 1]);
  2474. }
  2475. // if the first and last point are the same close the path - much neater :)
  2476. if(points[0] == points[points.length-2] && points[1] == points[points.length-1])
  2477. {
  2478. context.closePath();
  2479. }
  2480. if(data.fill)
  2481. {
  2482. context.globalAlpha = data.fillAlpha * worldAlpha;
  2483. context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
  2484. context.fill();
  2485. }
  2486. if(data.lineWidth)
  2487. {
  2488. context.globalAlpha = data.lineAlpha * worldAlpha;
  2489. context.stroke();
  2490. }
  2491. }
  2492. else if(data.type == PIXI.Graphics.RECT)
  2493. {
  2494. if(data.fillColor || data.fillColor === 0)
  2495. {
  2496. context.globalAlpha = data.fillAlpha * worldAlpha;
  2497. context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
  2498. context.fillRect(points[0], points[1], points[2], points[3]);
  2499. }
  2500. if(data.lineWidth)
  2501. {
  2502. context.globalAlpha = data.lineAlpha * worldAlpha;
  2503. context.strokeRect(points[0], points[1], points[2], points[3]);
  2504. }
  2505. }
  2506. else if(data.type == PIXI.Graphics.CIRC)
  2507. {
  2508. // TODO - need to be Undefined!
  2509. context.beginPath();
  2510. context.arc(points[0], points[1], points[2],0,2*Math.PI);
  2511. context.closePath();
  2512. if(data.fill)
  2513. {
  2514. context.globalAlpha = data.fillAlpha * worldAlpha;
  2515. context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
  2516. context.fill();
  2517. }
  2518. if(data.lineWidth)
  2519. {
  2520. context.globalAlpha = data.lineAlpha * worldAlpha;
  2521. context.stroke();
  2522. }
  2523. }
  2524. else if(data.type == PIXI.Graphics.ELIP)
  2525. {
  2526. // elipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  2527. var elipseData = data.points;
  2528. var w = elipseData[2] * 2;
  2529. var h = elipseData[3] * 2;
  2530. var x = elipseData[0] - w/2;
  2531. var y = elipseData[1] - h/2;
  2532. context.beginPath();
  2533. var kappa = .5522848,
  2534. ox = (w / 2) * kappa, // control point offset horizontal
  2535. oy = (h / 2) * kappa, // control point offset vertical
  2536. xe = x + w, // x-end
  2537. ye = y + h, // y-end
  2538. xm = x + w / 2, // x-middle
  2539. ym = y + h / 2; // y-middle
  2540. context.moveTo(x, ym);
  2541. context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  2542. context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  2543. context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  2544. context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  2545. context.closePath();
  2546. if(data.fill)
  2547. {
  2548. context.globalAlpha = data.fillAlpha * worldAlpha;
  2549. context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
  2550. context.fill();
  2551. }
  2552. if(data.lineWidth)
  2553. {
  2554. context.globalAlpha = data.lineAlpha * worldAlpha;
  2555. context.stroke();
  2556. }
  2557. }
  2558. };
  2559. }
  2560. /*
  2561. * Renders a graphics mask
  2562. *
  2563. * @static
  2564. * @private
  2565. * @method renderGraphicsMask
  2566. * @param graphics {Graphics}
  2567. * @param context {Context2D}
  2568. */
  2569. PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context)
  2570. {
  2571. var worldAlpha = graphics.worldAlpha;
  2572. var len = graphics.graphicsData.length;
  2573. if(len === 0)return;
  2574. if(len > 1)
  2575. {
  2576. len = 1;
  2577. console.log("Pixi.js warning: masks in canvas can only mask using the first path in the graphics object")
  2578. }
  2579. for (var i=0; i < 1; i++)
  2580. {
  2581. var data = graphics.graphicsData[i];
  2582. var points = data.points;
  2583. if(data.type == PIXI.Graphics.POLY)
  2584. {
  2585. context.beginPath();
  2586. context.moveTo(points[0], points[1]);
  2587. for (var j=1; j < points.length/2; j++)
  2588. {
  2589. context.lineTo(points[j * 2], points[j * 2 + 1]);
  2590. }
  2591. // if the first and last point are the same close the path - much neater :)
  2592. if(points[0] == points[points.length-2] && points[1] == points[points.length-1])
  2593. {
  2594. context.closePath();
  2595. }
  2596. }
  2597. else if(data.type == PIXI.Graphics.RECT)
  2598. {
  2599. context.beginPath();
  2600. context.rect(points[0], points[1], points[2], points[3]);
  2601. context.closePath();
  2602. }
  2603. else if(data.type == PIXI.Graphics.CIRC)
  2604. {
  2605. // TODO - need to be Undefined!
  2606. context.beginPath();
  2607. context.arc(points[0], points[1], points[2],0,2*Math.PI);
  2608. context.closePath();
  2609. }
  2610. else if(data.type == PIXI.Graphics.ELIP)
  2611. {
  2612. // elipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  2613. var elipseData = data.points;
  2614. var w = elipseData[2] * 2;
  2615. var h = elipseData[3] * 2;
  2616. var x = elipseData[0] - w/2;
  2617. var y = elipseData[1] - h/2;
  2618. context.beginPath();
  2619. var kappa = .5522848,
  2620. ox = (w / 2) * kappa, // control point offset horizontal
  2621. oy = (h / 2) * kappa, // control point offset vertical
  2622. xe = x + w, // x-end
  2623. ye = y + h, // y-end
  2624. xm = x + w / 2, // x-middle
  2625. ym = y + h / 2; // y-middle
  2626. context.moveTo(x, ym);
  2627. context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  2628. context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  2629. context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  2630. context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  2631. context.closePath();
  2632. }
  2633. };
  2634. }
  2635. /**
  2636. * @author Mat Groves http://matgroves.com/ @Doormat23
  2637. */
  2638. /**
  2639. * the CanvasRenderer draws the stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL.
  2640. * Dont forget to add the view to your DOM or you will not see anything :)
  2641. *
  2642. * @class CanvasRenderer
  2643. * @constructor
  2644. * @param width=0 {Number} the width of the canvas view
  2645. * @param height=0 {Number} the height of the canvas view
  2646. * @param view {Canvas} the canvas to use as a view, optional
  2647. * @param transparent=false {Boolean} the transparency of the render view, default false
  2648. */
  2649. PIXI.CanvasRenderer = function(width, height, view, transparent)
  2650. {
  2651. this.transparent = transparent;
  2652. /**
  2653. * The width of the canvas view
  2654. *
  2655. * @property width
  2656. * @type Number
  2657. * @default 800
  2658. */
  2659. this.width = width || 800;
  2660. /**
  2661. * The height of the canvas view
  2662. *
  2663. * @property height
  2664. * @type Number
  2665. * @default 600
  2666. */
  2667. this.height = height || 600;
  2668. /**
  2669. * The canvas element that the everything is drawn to
  2670. *
  2671. * @property view
  2672. * @type Canvas
  2673. */
  2674. this.view = view || document.createElement( 'canvas' );
  2675. /**
  2676. * The canvas context that the everything is drawn to
  2677. * @property context
  2678. * @type Canvas 2d Context
  2679. */
  2680. this.context = this.view.getContext("2d");
  2681. this.refresh = true;
  2682. // hack to enable some hardware acceleration!
  2683. //this.view.style["transform"] = "translatez(0)";
  2684. this.view.width = this.width;
  2685. this.view.height = this.height;
  2686. this.count = 0;
  2687. }
  2688. // constructor
  2689. PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer;
  2690. /**
  2691. * Renders the stage to its canvas view
  2692. *
  2693. * @method render
  2694. * @param stage {Stage} the Stage element to be rendered
  2695. */
  2696. PIXI.CanvasRenderer.prototype.render = function(stage)
  2697. {
  2698. //stage.__childrenAdded = [];
  2699. //stage.__childrenRemoved = [];
  2700. // update textures if need be
  2701. PIXI.texturesToUpdate = [];
  2702. PIXI.texturesToDestroy = [];
  2703. PIXI.visibleCount++;
  2704. stage.updateTransform();
  2705. // update the background color
  2706. if(this.view.style.backgroundColor!=stage.backgroundColorString && !this.transparent)this.view.style.backgroundColor = stage.backgroundColorString;
  2707. this.context.setTransform(1,0,0,1,0,0);
  2708. this.context.clearRect(0, 0, this.width, this.height)
  2709. this.renderDisplayObject(stage);
  2710. //as
  2711. // run interaction!
  2712. if(stage.interactive)
  2713. {
  2714. //need to add some events!
  2715. if(!stage._interactiveEventsAdded)
  2716. {
  2717. stage._interactiveEventsAdded = true;
  2718. stage.interactionManager.setTarget(this);
  2719. }
  2720. }
  2721. // remove frame updates..
  2722. if(PIXI.Texture.frameUpdates.length > 0)
  2723. {
  2724. PIXI.Texture.frameUpdates = [];
  2725. }
  2726. }
  2727. /**
  2728. * resizes the canvas view to the specified width and height
  2729. *
  2730. * @method resize
  2731. * @param width {Number} the new width of the canvas view
  2732. * @param height {Number} the new height of the canvas view
  2733. */
  2734. PIXI.CanvasRenderer.prototype.resize = function(width, height)
  2735. {
  2736. this.width = width;
  2737. this.height = height;
  2738. this.view.width = width;
  2739. this.view.height = height;
  2740. }
  2741. /**
  2742. * Renders a display object
  2743. *
  2744. * @method renderDisplayObject
  2745. * @param displayObject {DisplayObject} The displayObject to render
  2746. * @private
  2747. */
  2748. PIXI.CanvasRenderer.prototype.renderDisplayObject = function(displayObject)
  2749. {
  2750. // no loger recurrsive!
  2751. var transform;
  2752. var context = this.context;
  2753. context.globalCompositeOperation = 'source-over';
  2754. // one the display object hits this. we can break the loop
  2755. var testObject = displayObject.last._iNext;
  2756. displayObject = displayObject.first;
  2757. do
  2758. {
  2759. transform = displayObject.worldTransform;
  2760. if(!displayObject.visible)
  2761. {
  2762. displayObject = displayObject.last._iNext;
  2763. continue;
  2764. }
  2765. if(!displayObject.renderable)
  2766. {
  2767. displayObject = displayObject._iNext;
  2768. continue;
  2769. }
  2770. if(displayObject instanceof PIXI.Sprite)
  2771. {
  2772. var frame = displayObject.texture.frame;
  2773. if(frame && frame.width && frame.height)
  2774. {
  2775. context.globalAlpha = displayObject.worldAlpha;
  2776. context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5]);
  2777. context.drawImage(displayObject.texture.baseTexture.source,
  2778. frame.x,
  2779. frame.y,
  2780. frame.width,
  2781. frame.height,
  2782. (displayObject.anchor.x) * -frame.width,
  2783. (displayObject.anchor.y) * -frame.height,
  2784. frame.width,
  2785. frame.height);
  2786. }
  2787. }
  2788. else if(displayObject instanceof PIXI.Strip)
  2789. {
  2790. context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5])
  2791. this.renderStrip(displayObject);
  2792. }
  2793. else if(displayObject instanceof PIXI.TilingSprite)
  2794. {
  2795. context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5])
  2796. this.renderTilingSprite(displayObject);
  2797. }
  2798. else if(displayObject instanceof PIXI.CustomRenderable)
  2799. {
  2800. context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5]);
  2801. displayObject.renderCanvas(this);
  2802. }
  2803. else if(displayObject instanceof PIXI.Graphics)
  2804. {
  2805. context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5])
  2806. PIXI.CanvasGraphics.renderGraphics(displayObject, context);
  2807. }
  2808. else if(displayObject instanceof PIXI.FilterBlock)
  2809. {
  2810. if(displayObject.data instanceof PIXI.Graphics)
  2811. {
  2812. var mask = displayObject.data;
  2813. if(displayObject.open)
  2814. {
  2815. context.save();
  2816. var cacheAlpha = mask.alpha;
  2817. var maskTransform = mask.worldTransform;
  2818. context.setTransform(maskTransform[0], maskTransform[3], maskTransform[1], maskTransform[4], maskTransform[2], maskTransform[5])
  2819. mask.worldAlpha = 0.5;
  2820. context.worldAlpha = 0;
  2821. PIXI.CanvasGraphics.renderGraphicsMask(mask, context);
  2822. context.clip();
  2823. mask.worldAlpha = cacheAlpha;
  2824. }
  2825. else
  2826. {
  2827. context.restore();
  2828. }
  2829. }
  2830. else
  2831. {
  2832. // only masks supported right now!
  2833. }
  2834. }
  2835. // count++
  2836. displayObject = displayObject._iNext;
  2837. }
  2838. while(displayObject != testObject)
  2839. }
  2840. /**
  2841. * Renders a flat strip
  2842. *
  2843. * @method renderStripFlat
  2844. * @param strip {Strip} The Strip to render
  2845. * @private
  2846. */
  2847. PIXI.CanvasRenderer.prototype.renderStripFlat = function(strip)
  2848. {
  2849. var context = this.context;
  2850. var verticies = strip.verticies;
  2851. var uvs = strip.uvs;
  2852. var length = verticies.length/2;
  2853. this.count++;
  2854. context.beginPath();
  2855. for (var i=1; i < length-2; i++)
  2856. {
  2857. // draw some triangles!
  2858. var index = i*2;
  2859. var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4];
  2860. var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5];
  2861. context.moveTo(x0, y0);
  2862. context.lineTo(x1, y1);
  2863. context.lineTo(x2, y2);
  2864. };
  2865. context.fillStyle = "#FF0000";
  2866. context.fill();
  2867. context.closePath();
  2868. }
  2869. /**
  2870. * Renders a tiling sprite
  2871. *
  2872. * @method renderTilingSprite
  2873. * @param sprite {TilingSprite} The tilingsprite to render
  2874. * @private
  2875. */
  2876. PIXI.CanvasRenderer.prototype.renderTilingSprite = function(sprite)
  2877. {
  2878. var context = this.context;
  2879. context.globalAlpha = sprite.worldAlpha;
  2880. if(!sprite.__tilePattern) sprite.__tilePattern = context.createPattern(sprite.texture.baseTexture.source, "repeat");
  2881. context.beginPath();
  2882. var tilePosition = sprite.tilePosition;
  2883. var tileScale = sprite.tileScale;
  2884. // offset
  2885. context.scale(tileScale.x,tileScale.y);
  2886. context.translate(tilePosition.x, tilePosition.y);
  2887. context.fillStyle = sprite.__tilePattern;
  2888. context.fillRect(-tilePosition.x,-tilePosition.y,sprite.width / tileScale.x, sprite.height / tileScale.y);
  2889. context.scale(1/tileScale.x, 1/tileScale.y);
  2890. context.translate(-tilePosition.x, -tilePosition.y);
  2891. context.closePath();
  2892. }
  2893. /**
  2894. * Renders a strip
  2895. *
  2896. * @method renderStrip
  2897. * @param strip {Strip} The Strip to render
  2898. * @private
  2899. */
  2900. PIXI.CanvasRenderer.prototype.renderStrip = function(strip)
  2901. {
  2902. var context = this.context;
  2903. // draw triangles!!
  2904. var verticies = strip.verticies;
  2905. var uvs = strip.uvs;
  2906. var length = verticies.length/2;
  2907. this.count++;
  2908. for (var i=1; i < length-2; i++)
  2909. {
  2910. // draw some triangles!
  2911. var index = i*2;
  2912. var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4];
  2913. var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5];
  2914. var u0 = uvs[index] * strip.texture.width, u1 = uvs[index+2] * strip.texture.width, u2 = uvs[index+4]* strip.texture.width;
  2915. var v0 = uvs[index+1]* strip.texture.height, v1 = uvs[index+3] * strip.texture.height, v2 = uvs[index+5]* strip.texture.height;
  2916. context.save();
  2917. context.beginPath();
  2918. context.moveTo(x0, y0);
  2919. context.lineTo(x1, y1);
  2920. context.lineTo(x2, y2);
  2921. context.closePath();
  2922. context.clip();
  2923. // Compute matrix transform
  2924. var delta = u0*v1 + v0*u2 + u1*v2 - v1*u2 - v0*u1 - u0*v2;
  2925. var delta_a = x0*v1 + v0*x2 + x1*v2 - v1*x2 - v0*x1 - x0*v2;
  2926. var delta_b = u0*x1 + x0*u2 + u1*x2 - x1*u2 - x0*u1 - u0*x2;
  2927. var delta_c = u0*v1*x2 + v0*x1*u2 + x0*u1*v2 - x0*v1*u2 - v0*u1*x2 - u0*x1*v2;
  2928. var delta_d = y0*v1 + v0*y2 + y1*v2 - v1*y2 - v0*y1 - y0*v2;
  2929. var delta_e = u0*y1 + y0*u2 + u1*y2 - y1*u2 - y0*u1 - u0*y2;
  2930. var delta_f = u0*v1*y2 + v0*y1*u2 + y0*u1*v2 - y0*v1*u2 - v0*u1*y2 - u0*y1*v2;
  2931. context.transform(delta_a/delta, delta_d/delta,
  2932. delta_b/delta, delta_e/delta,
  2933. delta_c/delta, delta_f/delta);
  2934. context.drawImage(strip.texture.baseTexture.source, 0, 0);
  2935. context.restore();
  2936. };
  2937. }
  2938. /**
  2939. * @author Mat Groves http://matgroves.com/ @Doormat23
  2940. * @author Richard Davey http://www.photonstorm.com @photonstorm
  2941. */
  2942. /**
  2943. * @class PIXI.PixiShader
  2944. * @constructor
  2945. */
  2946. PIXI.PixiShader = function()
  2947. {
  2948. /**
  2949. * @property {any} program - The WebGL program.
  2950. */
  2951. this.program;
  2952. /**
  2953. * @property {array} fragmentSrc - The fragment shader.
  2954. */
  2955. this.fragmentSrc = [
  2956. "precision lowp float;",
  2957. "varying vec2 vTextureCoord;",
  2958. "varying float vColor;",
  2959. "uniform sampler2D uSampler;",
  2960. "void main(void) {",
  2961. "gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;",
  2962. "}"
  2963. ];
  2964. /**
  2965. * @property {number} textureCount - A local texture counter for multi-texture shaders.
  2966. */
  2967. this.textureCount = 0;
  2968. };
  2969. /**
  2970. * @method PIXI.PixiShader#init
  2971. */
  2972. PIXI.PixiShader.prototype.init = function()
  2973. {
  2974. var program = PIXI.compileProgram(this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc)
  2975. var gl = PIXI.gl;
  2976. gl.useProgram(program);
  2977. // get and store the uniforms for the shader
  2978. this.uSampler = gl.getUniformLocation(program, "uSampler");
  2979. this.projectionVector = gl.getUniformLocation(program, "projectionVector");
  2980. this.offsetVector = gl.getUniformLocation(program, "offsetVector");
  2981. this.dimensions = gl.getUniformLocation(program, "dimensions");
  2982. // get and store the attributes
  2983. this.aVertexPosition = gl.getAttribLocation(program, "aVertexPosition");
  2984. this.colorAttribute = gl.getAttribLocation(program, "aColor");
  2985. this.aTextureCoord = gl.getAttribLocation(program, "aTextureCoord");
  2986. // add those custom shaders!
  2987. for (var key in this.uniforms)
  2988. {
  2989. // get the uniform locations..
  2990. this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key);
  2991. }
  2992. this.initUniforms();
  2993. this.program = program;
  2994. };
  2995. /**
  2996. * Initialises the shader uniform values.
  2997. * Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/
  2998. * http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf
  2999. *
  3000. * @method PIXI.PixiShader#initUniforms
  3001. */
  3002. PIXI.PixiShader.prototype.initUniforms = function()
  3003. {
  3004. this.textureCount = 1;
  3005. var uniform;
  3006. for (var key in this.uniforms)
  3007. {
  3008. var uniform = this.uniforms[key];
  3009. var type = uniform.type;
  3010. if (type == 'sampler2D')
  3011. {
  3012. uniform._init = false;
  3013. if (uniform.value !== null)
  3014. {
  3015. this.initSampler2D(uniform);
  3016. }
  3017. }
  3018. else if (type == 'mat2' || type == 'mat3' || type == 'mat4')
  3019. {
  3020. // These require special handling
  3021. uniform.glMatrix = true;
  3022. uniform.glValueLength = 1;
  3023. if (type == 'mat2')
  3024. {
  3025. uniform.glFunc = PIXI.gl.uniformMatrix2fv;
  3026. }
  3027. else if (type == 'mat3')
  3028. {
  3029. uniform.glFunc = PIXI.gl.uniformMatrix3fv;
  3030. }
  3031. else if (type == 'mat4')
  3032. {
  3033. uniform.glFunc = PIXI.gl.uniformMatrix4fv;
  3034. }
  3035. }
  3036. else
  3037. {
  3038. // GL function reference
  3039. uniform.glFunc = PIXI.gl['uniform' + type];
  3040. if (type == '2f' || type == '2i')
  3041. {
  3042. uniform.glValueLength = 2;
  3043. }
  3044. else if (type == '3f' || type == '3i')
  3045. {
  3046. uniform.glValueLength = 3;
  3047. }
  3048. else if (type == '4f' || type == '4i')
  3049. {
  3050. uniform.glValueLength = 4;
  3051. }
  3052. else
  3053. {
  3054. uniform.glValueLength = 1;
  3055. }
  3056. }
  3057. }
  3058. };
  3059. /**
  3060. * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture is has loaded)
  3061. *
  3062. * @method PIXI.PixiShader#initSampler2D
  3063. */
  3064. PIXI.PixiShader.prototype.initSampler2D = function(uniform)
  3065. {
  3066. if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded)
  3067. {
  3068. return;
  3069. }
  3070. PIXI.gl.activeTexture(PIXI.gl['TEXTURE' + this.textureCount]);
  3071. PIXI.gl.bindTexture(PIXI.gl.TEXTURE_2D, uniform.value.baseTexture._glTexture);
  3072. // Extended texture data
  3073. if (uniform.textureData)
  3074. {
  3075. var data = uniform.textureData;
  3076. // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D);
  3077. // GLTextureLinear = mag/min linear, wrap clamp
  3078. // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat
  3079. // GLTextureNearest = mag/min nearest, wrap clamp
  3080. // AudioTexture = whatever + luminance + width 512, height 2, border 0
  3081. // KeyTexture = whatever + luminance + width 256, height 2, border 0
  3082. // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST
  3083. // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT
  3084. var magFilter = (data.magFilter) ? data.magFilter : PIXI.gl.LINEAR;
  3085. var minFilter = (data.minFilter) ? data.minFilter : PIXI.gl.LINEAR;
  3086. var wrapS = (data.wrapS) ? data.wrapS : PIXI.gl.CLAMP_TO_EDGE;
  3087. var wrapT = (data.wrapT) ? data.wrapT : PIXI.gl.CLAMP_TO_EDGE;
  3088. var format = (data.luminance) ? PIXI.gl.LUMINANCE : PIXI.gl.RGBA;
  3089. if (data.repeat)
  3090. {
  3091. wrapS = PIXI.gl.REPEAT;
  3092. wrapT = PIXI.gl.REPEAT;
  3093. }
  3094. PIXI.gl.pixelStorei(PIXI.gl.UNPACK_FLIP_Y_WEBGL, false);
  3095. if (data.width)
  3096. {
  3097. var width = (data.width) ? data.width : 512;
  3098. var height = (data.height) ? data.height : 2;
  3099. var border = (data.border) ? data.border : 0;
  3100. // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels);
  3101. PIXI.gl.texImage2D(PIXI.gl.TEXTURE_2D, 0, format, width, height, border, format, PIXI.gl.UNSIGNED_BYTE, null);
  3102. }
  3103. else
  3104. {
  3105. // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels);
  3106. PIXI.gl.texImage2D(PIXI.gl.TEXTURE_2D, 0, format, PIXI.gl.RGBA, PIXI.gl.UNSIGNED_BYTE, uniform.value.baseTexture.source);
  3107. }
  3108. PIXI.gl.texParameteri(PIXI.gl.TEXTURE_2D, PIXI.gl.TEXTURE_MAG_FILTER, magFilter);
  3109. PIXI.gl.texParameteri(PIXI.gl.TEXTURE_2D, PIXI.gl.TEXTURE_MIN_FILTER, minFilter);
  3110. PIXI.gl.texParameteri(PIXI.gl.TEXTURE_2D, PIXI.gl.TEXTURE_WRAP_S, wrapS);
  3111. PIXI.gl.texParameteri(PIXI.gl.TEXTURE_2D, PIXI.gl.TEXTURE_WRAP_T, wrapT);
  3112. }
  3113. PIXI.gl.uniform1i(uniform.uniformLocation, this.textureCount);
  3114. uniform._init = true;
  3115. this.textureCount++;
  3116. };
  3117. /**
  3118. * Updates the shader uniform values.
  3119. *
  3120. * @method PIXI.PixiShader#syncUniforms
  3121. */
  3122. PIXI.PixiShader.prototype.syncUniforms = function()
  3123. {
  3124. this.textureCount = 1;
  3125. var uniform;
  3126. // This would probably be faster in an array and it would guarantee key order
  3127. for (var key in this.uniforms)
  3128. {
  3129. uniform = this.uniforms[key];
  3130. if (uniform.glValueLength == 1)
  3131. {
  3132. if (uniform.glMatrix === true)
  3133. {
  3134. uniform.glFunc.call(PIXI.gl, uniform.uniformLocation, uniform.transpose, uniform.value);
  3135. }
  3136. else
  3137. {
  3138. uniform.glFunc.call(PIXI.gl, uniform.uniformLocation, uniform.value);
  3139. }
  3140. }
  3141. else if (uniform.glValueLength == 2)
  3142. {
  3143. uniform.glFunc.call(PIXI.gl, uniform.uniformLocation, uniform.value.x, uniform.value.y);
  3144. }
  3145. else if (uniform.glValueLength == 3)
  3146. {
  3147. uniform.glFunc.call(PIXI.gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z);
  3148. }
  3149. else if (uniform.glValueLength == 4)
  3150. {
  3151. uniform.glFunc.call(PIXI.gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z, uniform.value.w);
  3152. }
  3153. else if (uniform.type == 'sampler2D')
  3154. {
  3155. if (uniform._init)
  3156. {
  3157. PIXI.gl.activeTexture(PIXI.gl['TEXTURE' + this.textureCount]);
  3158. PIXI.gl.bindTexture(PIXI.gl.TEXTURE_2D, uniform.value.baseTexture._glTexture);
  3159. PIXI.gl.uniform1i(uniform.uniformLocation, this.textureCount);
  3160. this.textureCount++;
  3161. }
  3162. else
  3163. {
  3164. this.initSampler2D(uniform);
  3165. }
  3166. }
  3167. }
  3168. };
  3169. PIXI.PixiShader.defaultVertexSrc = [
  3170. "attribute vec2 aVertexPosition;",
  3171. "attribute vec2 aTextureCoord;",
  3172. "attribute float aColor;",
  3173. "uniform vec2 projectionVector;",
  3174. "uniform vec2 offsetVector;",
  3175. "varying vec2 vTextureCoord;",
  3176. "varying float vColor;",
  3177. "const vec2 center = vec2(-1.0, 1.0);",
  3178. "void main(void) {",
  3179. "gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);",
  3180. "vTextureCoord = aTextureCoord;",
  3181. "vColor = aColor;",
  3182. "}"
  3183. ];
  3184. /**
  3185. * @author Mat Groves http://matgroves.com/ @Doormat23
  3186. */
  3187. PIXI.PrimitiveShader = function()
  3188. {
  3189. // the webGL program..
  3190. this.program;
  3191. this.fragmentSrc = [
  3192. "precision mediump float;",
  3193. "varying vec4 vColor;",
  3194. "void main(void) {",
  3195. "gl_FragColor = vColor;",
  3196. "}"
  3197. ];
  3198. this.vertexSrc = [
  3199. "attribute vec2 aVertexPosition;",
  3200. "attribute vec4 aColor;",
  3201. "uniform mat3 translationMatrix;",
  3202. "uniform vec2 projectionVector;",
  3203. "uniform vec2 offsetVector;",
  3204. "uniform float alpha;",
  3205. "varying vec4 vColor;",
  3206. "void main(void) {",
  3207. "vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);",
  3208. "v -= offsetVector.xyx;",
  3209. "gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);",
  3210. "vColor = aColor * alpha;",
  3211. "}"
  3212. ];
  3213. }
  3214. PIXI.PrimitiveShader.prototype.init = function()
  3215. {
  3216. var program = PIXI.compileProgram(this.vertexSrc, this.fragmentSrc);
  3217. var gl = PIXI.gl;
  3218. gl.useProgram(program);
  3219. // get and store the uniforms for the shader
  3220. this.projectionVector = gl.getUniformLocation(program, "projectionVector");
  3221. this.offsetVector = gl.getUniformLocation(program, "offsetVector");
  3222. // get and store the attributes
  3223. this.aVertexPosition = gl.getAttribLocation(program, "aVertexPosition");
  3224. this.colorAttribute = gl.getAttribLocation(program, "aColor");
  3225. this.translationMatrix = gl.getUniformLocation(program, "translationMatrix");
  3226. this.alpha = gl.getUniformLocation(program, "alpha");
  3227. this.program = program;
  3228. }
  3229. /**
  3230. * @author Mat Groves http://matgroves.com/ @Doormat23
  3231. */
  3232. PIXI.StripShader = function()
  3233. {
  3234. // the webGL program..
  3235. this.program;
  3236. this.fragmentSrc = [
  3237. "precision mediump float;",
  3238. "varying vec2 vTextureCoord;",
  3239. "varying float vColor;",
  3240. "uniform float alpha;",
  3241. "uniform sampler2D uSampler;",
  3242. "void main(void) {",
  3243. "gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y));",
  3244. "gl_FragColor = gl_FragColor * alpha;",
  3245. "}"
  3246. ];
  3247. this.vertexSrc = [
  3248. "attribute vec2 aVertexPosition;",
  3249. "attribute vec2 aTextureCoord;",
  3250. "attribute float aColor;",
  3251. "uniform mat3 translationMatrix;",
  3252. "uniform vec2 projectionVector;",
  3253. "varying vec2 vTextureCoord;",
  3254. "varying vec2 offsetVector;",
  3255. "varying float vColor;",
  3256. "void main(void) {",
  3257. "vec3 v = translationMatrix * vec3(aVertexPosition, 1.0);",
  3258. "v -= offsetVector.xyx;",
  3259. "gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / projectionVector.y + 1.0 , 0.0, 1.0);",
  3260. "vTextureCoord = aTextureCoord;",
  3261. "vColor = aColor;",
  3262. "}"
  3263. ];
  3264. }
  3265. PIXI.StripShader.prototype.init = function()
  3266. {
  3267. var program = PIXI.compileProgram(this.vertexSrc, this.fragmentSrc)
  3268. var gl = PIXI.gl;
  3269. gl.useProgram(program);
  3270. // get and store the uniforms for the shader
  3271. this.uSampler = gl.getUniformLocation(program, "uSampler");
  3272. this.projectionVector = gl.getUniformLocation(program, "projectionVector");
  3273. this.offsetVector = gl.getUniformLocation(program, "offsetVector");
  3274. this.colorAttribute = gl.getAttribLocation(program, "aColor");
  3275. //this.dimensions = gl.getUniformLocation(this.program, "dimensions");
  3276. // get and store the attributes
  3277. this.aVertexPosition = gl.getAttribLocation(program, "aVertexPosition");
  3278. this.aTextureCoord = gl.getAttribLocation(program, "aTextureCoord");
  3279. this.translationMatrix = gl.getUniformLocation(program, "translationMatrix");
  3280. this.alpha = gl.getUniformLocation(program, "alpha");
  3281. this.program = program;
  3282. }
  3283. /**
  3284. * @author Mat Groves http://matgroves.com/ @Doormat23
  3285. */
  3286. PIXI._batchs = [];
  3287. /**
  3288. * @private
  3289. */
  3290. PIXI._getBatch = function(gl)
  3291. {
  3292. if(PIXI._batchs.length === 0)
  3293. {
  3294. return new PIXI.WebGLBatch(gl);
  3295. }
  3296. else
  3297. {
  3298. return PIXI._batchs.pop();
  3299. }
  3300. }
  3301. /**
  3302. * @private
  3303. */
  3304. PIXI._returnBatch = function(batch)
  3305. {
  3306. batch.clean();
  3307. PIXI._batchs.push(batch);
  3308. }
  3309. /**
  3310. * @private
  3311. */
  3312. PIXI._restoreBatchs = function(gl)
  3313. {
  3314. for (var i=0; i < PIXI._batchs.length; i++)
  3315. {
  3316. PIXI._batchs[i].restoreLostContext(gl);
  3317. };
  3318. }
  3319. /**
  3320. * A WebGLBatch Enables a group of sprites to be drawn using the same settings.
  3321. * if a group of sprites all have the same baseTexture and blendMode then they can be grouped into a batch.
  3322. * All the sprites in a batch can then be drawn in one go by the GPU which is hugely efficient. ALL sprites
  3323. * in the webGL renderer are added to a batch even if the batch only contains one sprite. Batching is handled
  3324. * automatically by the webGL renderer. A good tip is: the smaller the number of batchs there are, the faster
  3325. * the webGL renderer will run.
  3326. *
  3327. * @class WebGLBatch
  3328. * @constructor
  3329. * @param gl {WebGLContext} an instance of the webGL context
  3330. */
  3331. PIXI.WebGLBatch = function(gl)
  3332. {
  3333. this.gl = gl;
  3334. this.size = 0;
  3335. this.vertexBuffer = gl.createBuffer();
  3336. this.indexBuffer = gl.createBuffer();
  3337. this.uvBuffer = gl.createBuffer();
  3338. this.colorBuffer = gl.createBuffer();
  3339. this.blendMode = PIXI.blendModes.NORMAL;
  3340. this.dynamicSize = 1;
  3341. }
  3342. // constructor
  3343. PIXI.WebGLBatch.prototype.constructor = PIXI.WebGLBatch;
  3344. /**
  3345. * Cleans the batch so that is can be returned to an object pool and reused
  3346. *
  3347. * @method clean
  3348. */
  3349. PIXI.WebGLBatch.prototype.clean = function()
  3350. {
  3351. this.verticies = [];
  3352. this.uvs = [];
  3353. this.indices = [];
  3354. this.colors = [];
  3355. this.dynamicSize = 1;
  3356. this.texture = null;
  3357. this.last = null;
  3358. this.size = 0;
  3359. this.head;
  3360. this.tail;
  3361. }
  3362. /**
  3363. * Recreates the buffers in the event of a context loss
  3364. *
  3365. * @method restoreLostContext
  3366. * @param gl {WebGLContext}
  3367. */
  3368. PIXI.WebGLBatch.prototype.restoreLostContext = function(gl)
  3369. {
  3370. this.gl = gl;
  3371. this.vertexBuffer = gl.createBuffer();
  3372. this.indexBuffer = gl.createBuffer();
  3373. this.uvBuffer = gl.createBuffer();
  3374. this.colorBuffer = gl.createBuffer();
  3375. }
  3376. /**
  3377. * inits the batch's texture and blend mode based if the supplied sprite
  3378. *
  3379. * @method init
  3380. * @param sprite {Sprite} the first sprite to be added to the batch. Only sprites with
  3381. * the same base texture and blend mode will be allowed to be added to this batch
  3382. */
  3383. PIXI.WebGLBatch.prototype.init = function(sprite)
  3384. {
  3385. sprite.batch = this;
  3386. this.dirty = true;
  3387. this.blendMode = sprite.blendMode;
  3388. this.texture = sprite.texture.baseTexture;
  3389. this.head = sprite;
  3390. this.tail = sprite;
  3391. this.size = 1;
  3392. this.growBatch();
  3393. }
  3394. /**
  3395. * inserts a sprite before the specified sprite
  3396. *
  3397. * @method insertBefore
  3398. * @param sprite {Sprite} the sprite to be added
  3399. * @param nextSprite {nextSprite} the first sprite will be inserted before this sprite
  3400. */
  3401. PIXI.WebGLBatch.prototype.insertBefore = function(sprite, nextSprite)
  3402. {
  3403. this.size++;
  3404. sprite.batch = this;
  3405. this.dirty = true;
  3406. var tempPrev = nextSprite.__prev;
  3407. nextSprite.__prev = sprite;
  3408. sprite.__next = nextSprite;
  3409. if(tempPrev)
  3410. {
  3411. sprite.__prev = tempPrev;
  3412. tempPrev.__next = sprite;
  3413. }
  3414. else
  3415. {
  3416. this.head = sprite;
  3417. }
  3418. }
  3419. /**
  3420. * inserts a sprite after the specified sprite
  3421. *
  3422. * @method insertAfter
  3423. * @param sprite {Sprite} the sprite to be added
  3424. * @param previousSprite {Sprite} the first sprite will be inserted after this sprite
  3425. */
  3426. PIXI.WebGLBatch.prototype.insertAfter = function(sprite, previousSprite)
  3427. {
  3428. this.size++;
  3429. sprite.batch = this;
  3430. this.dirty = true;
  3431. var tempNext = previousSprite.__next;
  3432. previousSprite.__next = sprite;
  3433. sprite.__prev = previousSprite;
  3434. if(tempNext)
  3435. {
  3436. sprite.__next = tempNext;
  3437. tempNext.__prev = sprite;
  3438. }
  3439. else
  3440. {
  3441. this.tail = sprite
  3442. }
  3443. }
  3444. /**
  3445. * removes a sprite from the batch
  3446. *
  3447. * @method remove
  3448. * @param sprite {Sprite} the sprite to be removed
  3449. */
  3450. PIXI.WebGLBatch.prototype.remove = function(sprite)
  3451. {
  3452. this.size--;
  3453. if(this.size === 0)
  3454. {
  3455. sprite.batch = null;
  3456. sprite.__prev = null;
  3457. sprite.__next = null;
  3458. return;
  3459. }
  3460. if(sprite.__prev)
  3461. {
  3462. sprite.__prev.__next = sprite.__next;
  3463. }
  3464. else
  3465. {
  3466. this.head = sprite.__next;
  3467. this.head.__prev = null;
  3468. }
  3469. if(sprite.__next)
  3470. {
  3471. sprite.__next.__prev = sprite.__prev;
  3472. }
  3473. else
  3474. {
  3475. this.tail = sprite.__prev;
  3476. this.tail.__next = null
  3477. }
  3478. sprite.batch = null;
  3479. sprite.__next = null;
  3480. sprite.__prev = null;
  3481. this.dirty = true;
  3482. }
  3483. /**
  3484. * Splits the batch into two with the specified sprite being the start of the new batch.
  3485. *
  3486. * @method split
  3487. * @param sprite {Sprite} the sprite that indicates where the batch should be split
  3488. * @return {WebGLBatch} the new batch
  3489. */
  3490. PIXI.WebGLBatch.prototype.split = function(sprite)
  3491. {
  3492. this.dirty = true;
  3493. var batch = new PIXI.WebGLBatch(this.gl);
  3494. batch.init(sprite);
  3495. batch.texture = this.texture;
  3496. batch.tail = this.tail;
  3497. this.tail = sprite.__prev;
  3498. this.tail.__next = null;
  3499. sprite.__prev = null;
  3500. // return a splite batch!
  3501. // TODO this size is wrong!
  3502. // need to recalculate :/ problem with a linked list!
  3503. // unless it gets calculated in the "clean"?
  3504. // need to loop through items as there is no way to know the length on a linked list :/
  3505. var tempSize = 0;
  3506. while(sprite)
  3507. {
  3508. tempSize++;
  3509. sprite.batch = batch;
  3510. sprite = sprite.__next;
  3511. }
  3512. batch.size = tempSize;
  3513. this.size -= tempSize;
  3514. return batch;
  3515. }
  3516. /**
  3517. * Merges two batchs together
  3518. *
  3519. * @method merge
  3520. * @param batch {WebGLBatch} the batch that will be merged
  3521. */
  3522. PIXI.WebGLBatch.prototype.merge = function(batch)
  3523. {
  3524. this.dirty = true;
  3525. this.tail.__next = batch.head;
  3526. batch.head.__prev = this.tail;
  3527. this.size += batch.size;
  3528. this.tail = batch.tail;
  3529. var sprite = batch.head;
  3530. while(sprite)
  3531. {
  3532. sprite.batch = this;
  3533. sprite = sprite.__next;
  3534. }
  3535. }
  3536. /**
  3537. * Grows the size of the batch. As the elements in the batch cannot have a dynamic size this
  3538. * function is used to increase the size of the batch. It also creates a little extra room so
  3539. * that the batch does not need to be resized every time a sprite is added
  3540. *
  3541. * @method growBatch
  3542. */
  3543. PIXI.WebGLBatch.prototype.growBatch = function()
  3544. {
  3545. var gl = this.gl;
  3546. if( this.size == 1)
  3547. {
  3548. this.dynamicSize = 1;
  3549. }
  3550. else
  3551. {
  3552. this.dynamicSize = this.size * 1.5
  3553. }
  3554. // grow verts
  3555. this.verticies = new Float32Array(this.dynamicSize * 8);
  3556. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  3557. gl.bufferData(gl.ARRAY_BUFFER,this.verticies , gl.DYNAMIC_DRAW);
  3558. this.uvs = new Float32Array( this.dynamicSize * 8 );
  3559. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  3560. gl.bufferData(gl.ARRAY_BUFFER, this.uvs , gl.DYNAMIC_DRAW);
  3561. this.dirtyUVS = true;
  3562. this.colors = new Float32Array( this.dynamicSize * 4 );
  3563. gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
  3564. gl.bufferData(gl.ARRAY_BUFFER, this.colors , gl.DYNAMIC_DRAW);
  3565. this.dirtyColors = true;
  3566. this.indices = new Uint16Array(this.dynamicSize * 6);
  3567. var length = this.indices.length/6;
  3568. for (var i=0; i < length; i++)
  3569. {
  3570. var index2 = i * 6;
  3571. var index3 = i * 4;
  3572. this.indices[index2 + 0] = index3 + 0;
  3573. this.indices[index2 + 1] = index3 + 1;
  3574. this.indices[index2 + 2] = index3 + 2;
  3575. this.indices[index2 + 3] = index3 + 0;
  3576. this.indices[index2 + 4] = index3 + 2;
  3577. this.indices[index2 + 5] = index3 + 3;
  3578. };
  3579. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  3580. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  3581. }
  3582. /**
  3583. * Refresh's all the data in the batch and sync's it with the webGL buffers
  3584. *
  3585. * @method refresh
  3586. */
  3587. PIXI.WebGLBatch.prototype.refresh = function()
  3588. {
  3589. var gl = this.gl;
  3590. if (this.dynamicSize < this.size)
  3591. {
  3592. this.growBatch();
  3593. }
  3594. var indexRun = 0;
  3595. var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index;
  3596. var a, b, c, d, tx, ty;
  3597. var displayObject = this.head;
  3598. while(displayObject)
  3599. {
  3600. index = indexRun * 8;
  3601. var texture = displayObject.texture;
  3602. var frame = texture.frame;
  3603. var tw = texture.baseTexture.width;
  3604. var th = texture.baseTexture.height;
  3605. this.uvs[index + 0] = frame.x / tw;
  3606. this.uvs[index +1] = frame.y / th;
  3607. this.uvs[index +2] = (frame.x + frame.width) / tw;
  3608. this.uvs[index +3] = frame.y / th;
  3609. this.uvs[index +4] = (frame.x + frame.width) / tw;
  3610. this.uvs[index +5] = (frame.y + frame.height) / th;
  3611. this.uvs[index +6] = frame.x / tw;
  3612. this.uvs[index +7] = (frame.y + frame.height) / th;
  3613. displayObject.updateFrame = false;
  3614. colorIndex = indexRun * 4;
  3615. this.colors[colorIndex] = this.colors[colorIndex + 1] = this.colors[colorIndex + 2] = this.colors[colorIndex + 3] = displayObject.worldAlpha;
  3616. displayObject = displayObject.__next;
  3617. indexRun ++;
  3618. }
  3619. this.dirtyUVS = true;
  3620. this.dirtyColors = true;
  3621. }
  3622. /**
  3623. * Updates all the relevant geometry and uploads the data to the GPU
  3624. *
  3625. * @method update
  3626. */
  3627. PIXI.WebGLBatch.prototype.update = function()
  3628. {
  3629. var gl = this.gl;
  3630. var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index, index2, index3
  3631. var a, b, c, d, tx, ty;
  3632. var indexRun = 0;
  3633. var displayObject = this.head;
  3634. var verticies = this.verticies;
  3635. var uvs = this.uvs;
  3636. var colors = this.colors;
  3637. while(displayObject)
  3638. {
  3639. if(displayObject.vcount === PIXI.visibleCount)
  3640. {
  3641. width = displayObject.texture.frame.width;
  3642. height = displayObject.texture.frame.height;
  3643. // TODO trim??
  3644. aX = displayObject.anchor.x;// - displayObject.texture.trim.x
  3645. aY = displayObject.anchor.y; //- displayObject.texture.trim.y
  3646. w0 = width * (1-aX);
  3647. w1 = width * -aX;
  3648. h0 = height * (1-aY);
  3649. h1 = height * -aY;
  3650. index = indexRun * 8;
  3651. worldTransform = displayObject.worldTransform;
  3652. a = worldTransform[0];
  3653. b = worldTransform[3];
  3654. c = worldTransform[1];
  3655. d = worldTransform[4];
  3656. tx = worldTransform[2];
  3657. ty = worldTransform[5];
  3658. verticies[index + 0 ] = a * w1 + c * h1 + tx;
  3659. verticies[index + 1 ] = d * h1 + b * w1 + ty;
  3660. verticies[index + 2 ] = a * w0 + c * h1 + tx;
  3661. verticies[index + 3 ] = d * h1 + b * w0 + ty;
  3662. verticies[index + 4 ] = a * w0 + c * h0 + tx;
  3663. verticies[index + 5 ] = d * h0 + b * w0 + ty;
  3664. verticies[index + 6] = a * w1 + c * h0 + tx;
  3665. verticies[index + 7] = d * h0 + b * w1 + ty;
  3666. if(displayObject.updateFrame || displayObject.texture.updateFrame)
  3667. {
  3668. this.dirtyUVS = true;
  3669. var texture = displayObject.texture;
  3670. var frame = texture.frame;
  3671. var tw = texture.baseTexture.width;
  3672. var th = texture.baseTexture.height;
  3673. uvs[index + 0] = frame.x / tw;
  3674. uvs[index +1] = frame.y / th;
  3675. uvs[index +2] = (frame.x + frame.width) / tw;
  3676. uvs[index +3] = frame.y / th;
  3677. uvs[index +4] = (frame.x + frame.width) / tw;
  3678. uvs[index +5] = (frame.y + frame.height) / th;
  3679. uvs[index +6] = frame.x / tw;
  3680. uvs[index +7] = (frame.y + frame.height) / th;
  3681. displayObject.updateFrame = false;
  3682. }
  3683. // TODO this probably could do with some optimisation....
  3684. if(displayObject.cacheAlpha != displayObject.worldAlpha)
  3685. {
  3686. displayObject.cacheAlpha = displayObject.worldAlpha;
  3687. var colorIndex = indexRun * 4;
  3688. colors[colorIndex] = colors[colorIndex + 1] = colors[colorIndex + 2] = colors[colorIndex + 3] = displayObject.worldAlpha;
  3689. this.dirtyColors = true;
  3690. }
  3691. }
  3692. else
  3693. {
  3694. index = indexRun * 8;
  3695. verticies[index + 0 ] = verticies[index + 1 ] = verticies[index + 2 ] = verticies[index + 3 ] = verticies[index + 4 ] = verticies[index + 5 ] = verticies[index + 6] = verticies[index + 7] = 0;
  3696. }
  3697. indexRun++;
  3698. displayObject = displayObject.__next;
  3699. }
  3700. }
  3701. /**
  3702. * Draws the batch to the frame buffer
  3703. *
  3704. * @method render
  3705. */
  3706. PIXI.WebGLBatch.prototype.render = function(start, end)
  3707. {
  3708. start = start || 0;
  3709. if(end == undefined)end = this.size;
  3710. if(this.dirty)
  3711. {
  3712. this.refresh();
  3713. this.dirty = false;
  3714. }
  3715. if (this.size === 0)return;
  3716. this.update();
  3717. var gl = this.gl;
  3718. //TODO optimize this!
  3719. var shaderProgram = PIXI.defaultShader;
  3720. //gl.useProgram(shaderProgram);
  3721. // update the verts..
  3722. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  3723. // ok..
  3724. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.verticies)
  3725. gl.vertexAttribPointer(shaderProgram.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  3726. // update the uvs
  3727. //var isDefault = (shaderProgram == PIXI.shaderProgram)
  3728. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  3729. if(this.dirtyUVS)
  3730. {
  3731. this.dirtyUVS = false;
  3732. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvs);
  3733. }
  3734. gl.vertexAttribPointer(shaderProgram.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  3735. gl.activeTexture(gl.TEXTURE0);
  3736. gl.bindTexture(gl.TEXTURE_2D, this.texture._glTexture);
  3737. // update color!
  3738. gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
  3739. if(this.dirtyColors)
  3740. {
  3741. this.dirtyColors = false;
  3742. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.colors);
  3743. }
  3744. gl.vertexAttribPointer(shaderProgram.colorAttribute, 1, gl.FLOAT, false, 0, 0);
  3745. // dont need to upload!
  3746. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  3747. var len = end - start;
  3748. // DRAW THAT this!
  3749. gl.drawElements(gl.TRIANGLES, len * 6, gl.UNSIGNED_SHORT, start * 2 * 6 );
  3750. }
  3751. /**
  3752. * @author Mat Groves http://matgroves.com/ @Doormat23
  3753. */
  3754. PIXI.WebGLFilterManager = function(transparent)
  3755. {
  3756. this.transparent = transparent;
  3757. this.filterStack = [];
  3758. this.texturePool = [];
  3759. this.offsetX = 0;
  3760. this.offsetY = 0;
  3761. this.initShaderBuffers();
  3762. }
  3763. // API
  3764. PIXI.WebGLFilterManager.prototype.begin = function(projection, buffer)
  3765. {
  3766. this.width = projection.x * 2;
  3767. this.height = -projection.y * 2;
  3768. this.buffer = buffer;
  3769. }
  3770. PIXI.WebGLFilterManager.prototype.pushFilter = function(filterBlock)
  3771. {
  3772. var gl = PIXI.gl;
  3773. // filter program
  3774. // OPTIMISATION - the first filter is free if its a simple color change?
  3775. this.filterStack.push(filterBlock);
  3776. var filter = filterBlock.filterPasses[0];
  3777. this.offsetX += filterBlock.target.filterArea.x;
  3778. this.offsetY += filterBlock.target.filterArea.y;
  3779. var texture = this.texturePool.pop();
  3780. if(!texture)texture = new PIXI.FilterTexture(this.width, this.height);
  3781. gl.bindTexture(gl.TEXTURE_2D, texture.texture);
  3782. this.getBounds(filterBlock.target);
  3783. // addpadding?
  3784. //displayObject.filterArea.x
  3785. var filterArea = filterBlock.target.filterArea;
  3786. var padidng = filter.padding;
  3787. filterArea.x -= padidng;
  3788. filterArea.y -= padidng;
  3789. filterArea.width += padidng * 2;
  3790. filterArea.height += padidng * 2;
  3791. // cap filter to screen size..
  3792. if(filterArea.x < 0)filterArea.x = 0;
  3793. if(filterArea.width > this.width)filterArea.width = this.width;
  3794. if(filterArea.y < 0)filterArea.y = 0;
  3795. if(filterArea.height > this.height)filterArea.height = this.height;
  3796. //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3797. gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer);
  3798. // console.log(filterArea)
  3799. // set view port
  3800. gl.viewport(0, 0, filterArea.width, filterArea.height);
  3801. PIXI.projection.x = filterArea.width/2;
  3802. PIXI.projection.y = -filterArea.height/2;
  3803. PIXI.offset.x = -filterArea.x;
  3804. PIXI.offset.y = -filterArea.y;
  3805. //console.log(PIXI.defaultShader.projectionVector)
  3806. // update projection
  3807. gl.uniform2f(PIXI.defaultShader.projectionVector, filterArea.width/2, -filterArea.height/2);
  3808. gl.uniform2f(PIXI.defaultShader.offsetVector, -filterArea.x, -filterArea.y);
  3809. //PIXI.primitiveProgram
  3810. gl.colorMask(true, true, true, true);
  3811. gl.clearColor(0,0,0, 0);
  3812. gl.clear(gl.COLOR_BUFFER_BIT);
  3813. //filter.texture = texture;
  3814. filterBlock._glFilterTexture = texture;
  3815. //console.log("PUSH")
  3816. }
  3817. PIXI.WebGLFilterManager.prototype.popFilter = function()
  3818. {
  3819. var gl = PIXI.gl;
  3820. var filterBlock = this.filterStack.pop();
  3821. var filterArea = filterBlock.target.filterArea;
  3822. var texture = filterBlock._glFilterTexture;
  3823. if(filterBlock.filterPasses.length > 1)
  3824. {
  3825. gl.viewport(0, 0, filterArea.width, filterArea.height);
  3826. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  3827. this.vertexArray[0] = 0;
  3828. this.vertexArray[1] = filterArea.height;
  3829. this.vertexArray[2] = filterArea.width;
  3830. this.vertexArray[3] = filterArea.height;
  3831. this.vertexArray[4] = 0;
  3832. this.vertexArray[5] = 0;
  3833. this.vertexArray[6] = filterArea.width;
  3834. this.vertexArray[7] = 0;
  3835. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
  3836. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  3837. // nnow set the uvs..
  3838. this.uvArray[2] = filterArea.width/this.width;
  3839. this.uvArray[5] = filterArea.height/this.height;
  3840. this.uvArray[6] = filterArea.width/this.width;
  3841. this.uvArray[7] = filterArea.height/this.height;
  3842. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
  3843. var inputTexture = texture;
  3844. var outputTexture = this.texturePool.pop();
  3845. if(!outputTexture)outputTexture = new PIXI.FilterTexture(this.width, this.height);
  3846. // need to clear this FBO as it may have some left over elements from a prvious filter.
  3847. gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
  3848. gl.clear(gl.COLOR_BUFFER_BIT);
  3849. gl.disable(gl.BLEND);
  3850. for (var i = 0; i < filterBlock.filterPasses.length-1; i++)
  3851. {
  3852. var filterPass = filterBlock.filterPasses[i];
  3853. gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
  3854. // set texture
  3855. gl.activeTexture(gl.TEXTURE0);
  3856. gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture);
  3857. // draw texture..
  3858. //filterPass.applyFilterPass(filterArea.width, filterArea.height);
  3859. this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height);
  3860. // swap the textures..
  3861. var temp = inputTexture;
  3862. inputTexture = outputTexture;
  3863. outputTexture = temp;
  3864. };
  3865. gl.enable(gl.BLEND);
  3866. texture = inputTexture;
  3867. this.texturePool.push(outputTexture);
  3868. }
  3869. var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1];
  3870. this.offsetX -= filterArea.x;
  3871. this.offsetY -= filterArea.y;
  3872. var sizeX = this.width;
  3873. var sizeY = this.height;
  3874. var offsetX = 0;
  3875. var offsetY = 0;
  3876. var buffer = this.buffer;
  3877. // time to render the filters texture to the previous scene
  3878. if(this.filterStack.length === 0)
  3879. {
  3880. gl.colorMask(true, true, true, this.transparent);
  3881. }
  3882. else
  3883. {
  3884. var currentFilter = this.filterStack[this.filterStack.length-1];
  3885. var filterArea = currentFilter.target.filterArea;
  3886. sizeX = filterArea.width;
  3887. sizeY = filterArea.height;
  3888. offsetX = filterArea.x;
  3889. offsetY = filterArea.y;
  3890. buffer = currentFilter._glFilterTexture.frameBuffer;
  3891. }
  3892. // TODO need toremove thease global elements..
  3893. PIXI.projection.x = sizeX/2;
  3894. PIXI.projection.y = -sizeY/2;
  3895. PIXI.offset.x = offsetX;
  3896. PIXI.offset.y = offsetY;
  3897. var filterArea = filterBlock.target.filterArea;
  3898. var x = filterArea.x-offsetX;
  3899. var y = filterArea.y-offsetY;
  3900. // update the buffers..
  3901. // make sure to flip the y!
  3902. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  3903. this.vertexArray[0] = x;
  3904. this.vertexArray[1] = y + filterArea.height;
  3905. this.vertexArray[2] = x + filterArea.width;
  3906. this.vertexArray[3] = y + filterArea.height;
  3907. this.vertexArray[4] = x;
  3908. this.vertexArray[5] = y;
  3909. this.vertexArray[6] = x + filterArea.width;
  3910. this.vertexArray[7] = y;
  3911. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
  3912. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  3913. this.uvArray[2] = filterArea.width/this.width;
  3914. this.uvArray[5] = filterArea.height/this.height;
  3915. this.uvArray[6] = filterArea.width/this.width;
  3916. this.uvArray[7] = filterArea.height/this.height;
  3917. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
  3918. gl.viewport(0, 0, sizeX, sizeY);
  3919. // bind the buffer
  3920. gl.bindFramebuffer(gl.FRAMEBUFFER, buffer );
  3921. // set texture
  3922. gl.activeTexture(gl.TEXTURE0);
  3923. gl.bindTexture(gl.TEXTURE_2D, texture.texture);
  3924. // apply!
  3925. //filter.applyFilterPass(sizeX, sizeY);
  3926. this.applyFilterPass(filter, filterArea, sizeX, sizeY);
  3927. // now restore the regular shader..
  3928. gl.useProgram(PIXI.defaultShader.program);
  3929. gl.uniform2f(PIXI.defaultShader.projectionVector, sizeX/2, -sizeY/2);
  3930. gl.uniform2f(PIXI.defaultShader.offsetVector, -offsetX, -offsetY);
  3931. // return the texture to the pool
  3932. this.texturePool.push(texture);
  3933. filterBlock._glFilterTexture = null;
  3934. }
  3935. PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height)
  3936. {
  3937. // use program
  3938. var gl = PIXI.gl;
  3939. if(!filter.shader)
  3940. {
  3941. var shader = new PIXI.PixiShader();
  3942. shader.fragmentSrc = filter.fragmentSrc;
  3943. shader.uniforms = filter.uniforms;
  3944. shader.init();
  3945. filter.shader = shader;
  3946. }
  3947. var shader = filter.shader;
  3948. // set the shader
  3949. gl.useProgram(shader.program);
  3950. gl.uniform2f(shader.projectionVector, width/2, -height/2);
  3951. gl.uniform2f(shader.offsetVector, 0,0)
  3952. if(filter.uniforms.dimensions)
  3953. {
  3954. //console.log(filter.uniforms.dimensions)
  3955. filter.uniforms.dimensions.value[0] = this.width;//width;
  3956. filter.uniforms.dimensions.value[1] = this.height;//height;
  3957. filter.uniforms.dimensions.value[2] = this.vertexArray[0];
  3958. filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height;
  3959. // console.log(this.vertexArray[5])
  3960. }
  3961. shader.syncUniforms();
  3962. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  3963. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  3964. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  3965. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  3966. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  3967. // draw the filter...
  3968. gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  3969. }
  3970. PIXI.WebGLFilterManager.prototype.initShaderBuffers = function()
  3971. {
  3972. var gl = PIXI.gl;
  3973. // create some buffers
  3974. this.vertexBuffer = gl.createBuffer();
  3975. this.uvBuffer = gl.createBuffer();
  3976. this.indexBuffer = gl.createBuffer();
  3977. // bind and upload the vertexs..
  3978. // keep a refferance to the vertexFloatData..
  3979. this.vertexArray = new Float32Array([0.0, 0.0,
  3980. 1.0, 0.0,
  3981. 0.0, 1.0,
  3982. 1.0, 1.0]);
  3983. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  3984. gl.bufferData(
  3985. gl.ARRAY_BUFFER,
  3986. this.vertexArray,
  3987. gl.STATIC_DRAW);
  3988. // bind and upload the uv buffer
  3989. this.uvArray = new Float32Array([0.0, 0.0,
  3990. 1.0, 0.0,
  3991. 0.0, 1.0,
  3992. 1.0, 1.0]);
  3993. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  3994. gl.bufferData(
  3995. gl.ARRAY_BUFFER,
  3996. this.uvArray,
  3997. gl.STATIC_DRAW);
  3998. // bind and upload the index
  3999. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  4000. gl.bufferData(
  4001. gl.ELEMENT_ARRAY_BUFFER,
  4002. new Uint16Array([0, 1, 2, 1, 3, 2]),
  4003. gl.STATIC_DRAW);
  4004. }
  4005. PIXI.WebGLFilterManager.prototype.getBounds = function(displayObject)
  4006. {
  4007. // time to get the width and height of the object!
  4008. var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index, doTest;
  4009. var a, b, c, d, tx, ty, x1, x2, x3, x4, y1, y2, y3, y4;
  4010. var tempObject = displayObject.first;
  4011. var testObject = displayObject.last._iNext;
  4012. var maxX = -Infinity;
  4013. var maxY = -Infinity;
  4014. var minX = Infinity;
  4015. var minY = Infinity;
  4016. do
  4017. {
  4018. // TODO can be optimized! - what if there is no scale / rotation?
  4019. if(tempObject.visible)
  4020. {
  4021. if(tempObject instanceof PIXI.Sprite)
  4022. {
  4023. width = tempObject.texture.frame.width;
  4024. height = tempObject.texture.frame.height;
  4025. // TODO trim??
  4026. aX = tempObject.anchor.x;
  4027. aY = tempObject.anchor.y;
  4028. w0 = width * (1-aX);
  4029. w1 = width * -aX;
  4030. h0 = height * (1-aY);
  4031. h1 = height * -aY;
  4032. doTest = true;
  4033. }
  4034. else if(tempObject instanceof PIXI.Graphics)
  4035. {
  4036. tempObject.updateFilterBounds();
  4037. var bounds = tempObject.bounds;
  4038. width = bounds.width;
  4039. height = bounds.height;
  4040. w0 = bounds.x
  4041. w1 = bounds.x + bounds.width;
  4042. h0 = bounds.y
  4043. h1 = bounds.y + bounds.height;
  4044. doTest = true;
  4045. }
  4046. }
  4047. if(doTest)
  4048. {
  4049. worldTransform = tempObject.worldTransform;
  4050. a = worldTransform[0];
  4051. b = worldTransform[3];
  4052. c = worldTransform[1];
  4053. d = worldTransform[4];
  4054. tx = worldTransform[2];
  4055. ty = worldTransform[5];
  4056. x1 = a * w1 + c * h1 + tx;
  4057. y1 = d * h1 + b * w1 + ty;
  4058. x2 = a * w0 + c * h1 + tx;
  4059. y2 = d * h1 + b * w0 + ty;
  4060. x3 = a * w0 + c * h0 + tx;
  4061. y3 = d * h0 + b * w0 + ty;
  4062. x4 = a * w1 + c * h0 + tx;
  4063. y4 = d * h0 + b * w1 + ty;
  4064. minX = x1 < minX ? x1 : minX;
  4065. minX = x2 < minX ? x2 : minX;
  4066. minX = x3 < minX ? x3 : minX;
  4067. minX = x4 < minX ? x4 : minX;
  4068. minY = y1 < minY ? y1 : minY;
  4069. minY = y2 < minY ? y2 : minY;
  4070. minY = y3 < minY ? y3 : minY;
  4071. minY = y4 < minY ? y4 : minY;
  4072. maxX = x1 > maxX ? x1 : maxX;
  4073. maxX = x2 > maxX ? x2 : maxX;
  4074. maxX = x3 > maxX ? x3 : maxX;
  4075. maxX = x4 > maxX ? x4 : maxX;
  4076. maxY = y1 > maxY ? y1 : maxY;
  4077. maxY = y2 > maxY ? y2 : maxY;
  4078. maxY = y3 > maxY ? y3 : maxY;
  4079. maxY = y4 > maxY ? y4 : maxY;
  4080. }
  4081. doTest = false;
  4082. tempObject = tempObject._iNext;
  4083. }
  4084. while(tempObject != testObject)
  4085. // maximum bounds is the size of the screen..
  4086. //minX = minX > 0 ? minX : 0;
  4087. //minY = minY > 0 ? minY : 0;
  4088. displayObject.filterArea.x = minX;
  4089. displayObject.filterArea.y = minY;
  4090. // console.log(maxX+ " : " + minX)
  4091. displayObject.filterArea.width = maxX - minX;
  4092. displayObject.filterArea.height = maxY - minY;
  4093. }
  4094. PIXI.FilterTexture = function(width, height)
  4095. {
  4096. var gl = PIXI.gl;
  4097. // next time to create a frame buffer and texture
  4098. this.frameBuffer = gl.createFramebuffer();
  4099. this.texture = gl.createTexture();
  4100. gl.bindTexture(gl.TEXTURE_2D, this.texture);
  4101. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4102. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  4103. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4104. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4105. gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer );
  4106. gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer );
  4107. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);
  4108. this.resize(width, height);
  4109. }
  4110. PIXI.FilterTexture.prototype.resize = function(width, height)
  4111. {
  4112. this.width = width;
  4113. this.height = height;
  4114. var gl = PIXI.gl;
  4115. gl.bindTexture(gl.TEXTURE_2D, this.texture);
  4116. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4117. }
  4118. /**
  4119. * @author Mat Groves http://matgroves.com/ @Doormat23
  4120. */
  4121. /**
  4122. * A set of functions used by the webGL renderer to draw the primitive graphics data
  4123. *
  4124. * @class CanvasGraphics
  4125. */
  4126. PIXI.WebGLGraphics = function()
  4127. {
  4128. }
  4129. /**
  4130. * Renders the graphics object
  4131. *
  4132. * @static
  4133. * @private
  4134. * @method renderGraphics
  4135. * @param graphics {Graphics}
  4136. * @param projection {Object}
  4137. */
  4138. PIXI.WebGLGraphics.renderGraphics = function(graphics, projection)
  4139. {
  4140. var gl = PIXI.gl;
  4141. if(!graphics._webGL)graphics._webGL = {points:[], indices:[], lastIndex:0,
  4142. buffer:gl.createBuffer(),
  4143. indexBuffer:gl.createBuffer()};
  4144. if(graphics.dirty)
  4145. {
  4146. graphics.dirty = false;
  4147. if(graphics.clearDirty)
  4148. {
  4149. graphics.clearDirty = false;
  4150. graphics._webGL.lastIndex = 0;
  4151. graphics._webGL.points = [];
  4152. graphics._webGL.indices = [];
  4153. }
  4154. PIXI.WebGLGraphics.updateGraphics(graphics);
  4155. }
  4156. PIXI.activatePrimitiveShader();
  4157. // This could be speeded up fo sure!
  4158. var m = PIXI.mat3.clone(graphics.worldTransform);
  4159. PIXI.mat3.transpose(m);
  4160. // set the matrix transform for the
  4161. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  4162. gl.uniformMatrix3fv(PIXI.primitiveShader.translationMatrix, false, m);
  4163. gl.uniform2f(PIXI.primitiveShader.projectionVector, projection.x, -projection.y);
  4164. gl.uniform2f(PIXI.primitiveShader.offsetVector, -PIXI.offset.x, -PIXI.offset.y);
  4165. gl.uniform1f(PIXI.primitiveShader.alpha, graphics.worldAlpha);
  4166. gl.bindBuffer(gl.ARRAY_BUFFER, graphics._webGL.buffer);
  4167. gl.vertexAttribPointer(PIXI.primitiveShader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
  4168. gl.vertexAttribPointer(PIXI.primitiveShader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4);
  4169. // set the index buffer!
  4170. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, graphics._webGL.indexBuffer);
  4171. gl.drawElements(gl.TRIANGLE_STRIP, graphics._webGL.indices.length, gl.UNSIGNED_SHORT, 0 );
  4172. PIXI.deactivatePrimitiveShader();
  4173. // return to default shader...
  4174. // PIXI.activateShader(PIXI.defaultShader);
  4175. }
  4176. /**
  4177. * Updates the graphics object
  4178. *
  4179. * @static
  4180. * @private
  4181. * @method updateGraphics
  4182. * @param graphics {Graphics}
  4183. */
  4184. PIXI.WebGLGraphics.updateGraphics = function(graphics)
  4185. {
  4186. for (var i=graphics._webGL.lastIndex; i < graphics.graphicsData.length; i++)
  4187. {
  4188. var data = graphics.graphicsData[i];
  4189. if(data.type == PIXI.Graphics.POLY)
  4190. {
  4191. if(data.fill)
  4192. {
  4193. if(data.points.length>3)
  4194. PIXI.WebGLGraphics.buildPoly(data, graphics._webGL);
  4195. }
  4196. if(data.lineWidth > 0)
  4197. {
  4198. PIXI.WebGLGraphics.buildLine(data, graphics._webGL);
  4199. }
  4200. }
  4201. else if(data.type == PIXI.Graphics.RECT)
  4202. {
  4203. PIXI.WebGLGraphics.buildRectangle(data, graphics._webGL);
  4204. }
  4205. else if(data.type == PIXI.Graphics.CIRC || data.type == PIXI.Graphics.ELIP)
  4206. {
  4207. PIXI.WebGLGraphics.buildCircle(data, graphics._webGL);
  4208. }
  4209. };
  4210. graphics._webGL.lastIndex = graphics.graphicsData.length;
  4211. var gl = PIXI.gl;
  4212. graphics._webGL.glPoints = new Float32Array(graphics._webGL.points);
  4213. gl.bindBuffer(gl.ARRAY_BUFFER, graphics._webGL.buffer);
  4214. gl.bufferData(gl.ARRAY_BUFFER, graphics._webGL.glPoints, gl.STATIC_DRAW);
  4215. graphics._webGL.glIndicies = new Uint16Array(graphics._webGL.indices);
  4216. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, graphics._webGL.indexBuffer);
  4217. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, graphics._webGL.glIndicies, gl.STATIC_DRAW);
  4218. }
  4219. /**
  4220. * Builds a rectangle to draw
  4221. *
  4222. * @static
  4223. * @private
  4224. * @method buildRectangle
  4225. * @param graphics {Graphics}
  4226. * @param webGLData {Object}
  4227. */
  4228. PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData)
  4229. {
  4230. // --- //
  4231. // need to convert points to a nice regular data
  4232. //
  4233. var rectData = graphicsData.points;
  4234. var x = rectData[0];
  4235. var y = rectData[1];
  4236. var width = rectData[2];
  4237. var height = rectData[3];
  4238. if(graphicsData.fill)
  4239. {
  4240. var color = HEXtoRGB(graphicsData.fillColor);
  4241. var alpha = graphicsData.fillAlpha;
  4242. var r = color[0] * alpha;
  4243. var g = color[1] * alpha;
  4244. var b = color[2] * alpha;
  4245. var verts = webGLData.points;
  4246. var indices = webGLData.indices;
  4247. var vertPos = verts.length/6;
  4248. // start
  4249. verts.push(x, y);
  4250. verts.push(r, g, b, alpha);
  4251. verts.push(x + width, y);
  4252. verts.push(r, g, b, alpha);
  4253. verts.push(x , y + height);
  4254. verts.push(r, g, b, alpha);
  4255. verts.push(x + width, y + height);
  4256. verts.push(r, g, b, alpha);
  4257. // insert 2 dead triangles..
  4258. indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3)
  4259. }
  4260. if(graphicsData.lineWidth)
  4261. {
  4262. graphicsData.points = [x, y,
  4263. x + width, y,
  4264. x + width, y + height,
  4265. x, y + height,
  4266. x, y];
  4267. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  4268. }
  4269. }
  4270. /**
  4271. * Builds a circle to draw
  4272. *
  4273. * @static
  4274. * @private
  4275. * @method buildCircle
  4276. * @param graphics {Graphics}
  4277. * @param webGLData {Object}
  4278. */
  4279. PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData)
  4280. {
  4281. // --- //
  4282. // need to convert points to a nice regular data
  4283. //
  4284. var rectData = graphicsData.points;
  4285. var x = rectData[0];
  4286. var y = rectData[1];
  4287. var width = rectData[2];
  4288. var height = rectData[3];
  4289. var totalSegs = 40;
  4290. var seg = (Math.PI * 2) / totalSegs ;
  4291. if(graphicsData.fill)
  4292. {
  4293. var color = HEXtoRGB(graphicsData.fillColor);
  4294. var alpha = graphicsData.fillAlpha;
  4295. var r = color[0] * alpha;
  4296. var g = color[1] * alpha;
  4297. var b = color[2] * alpha;
  4298. var verts = webGLData.points;
  4299. var indices = webGLData.indices;
  4300. var vecPos = verts.length/6;
  4301. indices.push(vecPos);
  4302. for (var i=0; i < totalSegs + 1 ; i++)
  4303. {
  4304. verts.push(x,y, r, g, b, alpha);
  4305. verts.push(x + Math.sin(seg * i) * width,
  4306. y + Math.cos(seg * i) * height,
  4307. r, g, b, alpha);
  4308. indices.push(vecPos++, vecPos++);
  4309. };
  4310. indices.push(vecPos-1);
  4311. }
  4312. if(graphicsData.lineWidth)
  4313. {
  4314. graphicsData.points = [];
  4315. for (var i=0; i < totalSegs + 1; i++)
  4316. {
  4317. graphicsData.points.push(x + Math.sin(seg * i) * width,
  4318. y + Math.cos(seg * i) * height)
  4319. };
  4320. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  4321. }
  4322. }
  4323. /**
  4324. * Builds a line to draw
  4325. *
  4326. * @static
  4327. * @private
  4328. * @method buildLine
  4329. * @param graphics {Graphics}
  4330. * @param webGLData {Object}
  4331. */
  4332. PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData)
  4333. {
  4334. // TODO OPTIMISE!
  4335. var wrap = true;
  4336. var points = graphicsData.points;
  4337. if(points.length === 0)return;
  4338. // if the line width is an odd number add 0.5 to align to a whole pixel
  4339. if(graphicsData.lineWidth%2)
  4340. {
  4341. for (var i = 0; i < points.length; i++) {
  4342. points[i] += 0.5;
  4343. };
  4344. }
  4345. // get first and last point.. figure out the middle!
  4346. var firstPoint = new PIXI.Point( points[0], points[1] );
  4347. var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
  4348. // if the first point is the last point - goona have issues :)
  4349. if(firstPoint.x == lastPoint.x && firstPoint.y == lastPoint.y)
  4350. {
  4351. points.pop();
  4352. points.pop();
  4353. lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
  4354. var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5;
  4355. var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5;
  4356. points.unshift(midPointX, midPointY);
  4357. points.push(midPointX, midPointY)
  4358. }
  4359. var verts = webGLData.points;
  4360. var indices = webGLData.indices;
  4361. var length = points.length / 2;
  4362. var indexCount = points.length;
  4363. var indexStart = verts.length/6;
  4364. // DRAW the Line
  4365. var width = graphicsData.lineWidth / 2;
  4366. // sort color
  4367. var color = HEXtoRGB(graphicsData.lineColor);
  4368. var alpha = graphicsData.lineAlpha;
  4369. var r = color[0] * alpha;
  4370. var g = color[1] * alpha;
  4371. var b = color[2] * alpha;
  4372. var p1x, p1y, p2x, p2y, p3x, p3y;
  4373. var perpx, perpy, perp2x, perp2y, perp3x, perp3y;
  4374. var ipx, ipy;
  4375. var a1, b1, c1, a2, b2, c2;
  4376. var denom, pdist, dist;
  4377. p1x = points[0];
  4378. p1y = points[1];
  4379. p2x = points[2];
  4380. p2y = points[3];
  4381. perpx = -(p1y - p2y);
  4382. perpy = p1x - p2x;
  4383. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  4384. perpx /= dist;
  4385. perpy /= dist;
  4386. perpx *= width;
  4387. perpy *= width;
  4388. // start
  4389. verts.push(p1x - perpx , p1y - perpy,
  4390. r, g, b, alpha);
  4391. verts.push(p1x + perpx , p1y + perpy,
  4392. r, g, b, alpha);
  4393. for (var i = 1; i < length-1; i++)
  4394. {
  4395. p1x = points[(i-1)*2];
  4396. p1y = points[(i-1)*2 + 1];
  4397. p2x = points[(i)*2]
  4398. p2y = points[(i)*2 + 1]
  4399. p3x = points[(i+1)*2];
  4400. p3y = points[(i+1)*2 + 1];
  4401. perpx = -(p1y - p2y);
  4402. perpy = p1x - p2x;
  4403. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  4404. perpx /= dist;
  4405. perpy /= dist;
  4406. perpx *= width;
  4407. perpy *= width;
  4408. perp2x = -(p2y - p3y);
  4409. perp2y = p2x - p3x;
  4410. dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y);
  4411. perp2x /= dist;
  4412. perp2y /= dist;
  4413. perp2x *= width;
  4414. perp2y *= width;
  4415. a1 = (-perpy + p1y) - (-perpy + p2y);
  4416. b1 = (-perpx + p2x) - (-perpx + p1x);
  4417. c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y);
  4418. a2 = (-perp2y + p3y) - (-perp2y + p2y);
  4419. b2 = (-perp2x + p2x) - (-perp2x + p3x);
  4420. c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y);
  4421. denom = a1*b2 - a2*b1;
  4422. if(Math.abs(denom) < 0.1 )
  4423. {
  4424. denom+=10.1;
  4425. verts.push(p2x - perpx , p2y - perpy,
  4426. r, g, b, alpha);
  4427. verts.push(p2x + perpx , p2y + perpy,
  4428. r, g, b, alpha);
  4429. continue;
  4430. }
  4431. px = (b1*c2 - b2*c1)/denom;
  4432. py = (a2*c1 - a1*c2)/denom;
  4433. pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y);
  4434. if(pdist > 140 * 140)
  4435. {
  4436. perp3x = perpx - perp2x;
  4437. perp3y = perpy - perp2y;
  4438. dist = Math.sqrt(perp3x*perp3x + perp3y*perp3y);
  4439. perp3x /= dist;
  4440. perp3y /= dist;
  4441. perp3x *= width;
  4442. perp3y *= width;
  4443. verts.push(p2x - perp3x, p2y -perp3y);
  4444. verts.push(r, g, b, alpha);
  4445. verts.push(p2x + perp3x, p2y +perp3y);
  4446. verts.push(r, g, b, alpha);
  4447. verts.push(p2x - perp3x, p2y -perp3y);
  4448. verts.push(r, g, b, alpha);
  4449. indexCount++;
  4450. }
  4451. else
  4452. {
  4453. verts.push(px , py);
  4454. verts.push(r, g, b, alpha);
  4455. verts.push(p2x - (px-p2x), p2y - (py - p2y));
  4456. verts.push(r, g, b, alpha);
  4457. }
  4458. }
  4459. p1x = points[(length-2)*2]
  4460. p1y = points[(length-2)*2 + 1]
  4461. p2x = points[(length-1)*2]
  4462. p2y = points[(length-1)*2 + 1]
  4463. perpx = -(p1y - p2y)
  4464. perpy = p1x - p2x;
  4465. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  4466. perpx /= dist;
  4467. perpy /= dist;
  4468. perpx *= width;
  4469. perpy *= width;
  4470. verts.push(p2x - perpx , p2y - perpy)
  4471. verts.push(r, g, b, alpha);
  4472. verts.push(p2x + perpx , p2y + perpy)
  4473. verts.push(r, g, b, alpha);
  4474. indices.push(indexStart);
  4475. for (var i=0; i < indexCount; i++)
  4476. {
  4477. indices.push(indexStart++);
  4478. };
  4479. indices.push(indexStart-1);
  4480. }
  4481. /**
  4482. * Builds a polygon to draw
  4483. *
  4484. * @static
  4485. * @private
  4486. * @method buildPoly
  4487. * @param graphics {Graphics}
  4488. * @param webGLData {Object}
  4489. */
  4490. PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData)
  4491. {
  4492. var points = graphicsData.points;
  4493. if(points.length < 6)return;
  4494. // get first and last point.. figure out the middle!
  4495. var verts = webGLData.points;
  4496. var indices = webGLData.indices;
  4497. var length = points.length / 2;
  4498. // sort color
  4499. var color = HEXtoRGB(graphicsData.fillColor);
  4500. var alpha = graphicsData.fillAlpha;
  4501. var r = color[0] * alpha;
  4502. var g = color[1] * alpha;
  4503. var b = color[2] * alpha;
  4504. var triangles = PIXI.PolyK.Triangulate(points);
  4505. var vertPos = verts.length / 6;
  4506. for (var i=0; i < triangles.length; i+=3)
  4507. {
  4508. indices.push(triangles[i] + vertPos);
  4509. indices.push(triangles[i] + vertPos);
  4510. indices.push(triangles[i+1] + vertPos);
  4511. indices.push(triangles[i+2] +vertPos);
  4512. indices.push(triangles[i+2] + vertPos);
  4513. };
  4514. for (var i = 0; i < length; i++)
  4515. {
  4516. verts.push(points[i * 2], points[i * 2 + 1],
  4517. r, g, b, alpha);
  4518. };
  4519. }
  4520. function HEXtoRGB(hex) {
  4521. return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255];
  4522. }
  4523. /**
  4524. * @author Mat Groves http://matgroves.com/ @Doormat23
  4525. */
  4526. PIXI._defaultFrame = new PIXI.Rectangle(0,0,1,1);
  4527. // an instance of the gl context..
  4528. // only one at the moment :/
  4529. PIXI.gl;
  4530. /**
  4531. * the WebGLRenderer is draws the stage and all its content onto a webGL enabled canvas. This renderer
  4532. * should be used for browsers support webGL. This Render works by automatically managing webGLBatchs.
  4533. * So no need for Sprite Batch's or Sprite Cloud's
  4534. * Dont forget to add the view to your DOM or you will not see anything :)
  4535. *
  4536. * @class WebGLRenderer
  4537. * @constructor
  4538. * @param width=0 {Number} the width of the canvas view
  4539. * @param height=0 {Number} the height of the canvas view
  4540. * @param view {Canvas} the canvas to use as a view, optional
  4541. * @param transparent=false {Boolean} the transparency of the render view, default false
  4542. * @param antialias=false {Boolean} sets antialias (only applicable in chrome at the moment)
  4543. *
  4544. */
  4545. PIXI.WebGLRenderer = function(width, height, view, transparent, antialias)
  4546. {
  4547. // do a catch.. only 1 webGL renderer..
  4548. this.transparent = !!transparent;
  4549. this.width = width || 800;
  4550. this.height = height || 600;
  4551. this.view = view || document.createElement( 'canvas' );
  4552. this.view.width = this.width;
  4553. this.view.height = this.height;
  4554. // deal with losing context..
  4555. var scope = this;
  4556. this.view.addEventListener('webglcontextlost', function(event) { scope.handleContextLost(event); }, false)
  4557. this.view.addEventListener('webglcontextrestored', function(event) { scope.handleContextRestored(event); }, false)
  4558. this.batchs = [];
  4559. var options = {
  4560. alpha: this.transparent,
  4561. antialias:!!antialias, // SPEED UP??
  4562. premultipliedAlpha:false,
  4563. stencil:true
  4564. }
  4565. //try 'experimental-webgl'
  4566. try {
  4567. PIXI.gl = this.gl = this.view.getContext("experimental-webgl", options);
  4568. } catch (e) {
  4569. //try 'webgl'
  4570. try {
  4571. PIXI.gl = this.gl = this.view.getContext("webgl", options);
  4572. } catch (e) {
  4573. // fail, not able to get a context
  4574. throw new Error(" This browser does not support webGL. Try using the canvas renderer" + this);
  4575. }
  4576. }
  4577. PIXI.initDefaultShaders();
  4578. // PIXI.activateDefaultShader();
  4579. var gl = this.gl;
  4580. gl.useProgram(PIXI.defaultShader.program);
  4581. PIXI.WebGLRenderer.gl = gl;
  4582. this.batch = new PIXI.WebGLBatch(gl);
  4583. gl.disable(gl.DEPTH_TEST);
  4584. gl.disable(gl.CULL_FACE);
  4585. gl.enable(gl.BLEND);
  4586. gl.colorMask(true, true, true, this.transparent);
  4587. PIXI.projection = new PIXI.Point(400, 300);
  4588. PIXI.offset = new PIXI.Point(0, 0);
  4589. // TODO remove thease globals..
  4590. this.resize(this.width, this.height);
  4591. this.contextLost = false;
  4592. //PIXI.pushShader(PIXI.defaultShader);
  4593. this.stageRenderGroup = new PIXI.WebGLRenderGroup(this.gl, this.transparent);
  4594. // this.stageRenderGroup. = this.transparent
  4595. }
  4596. // constructor
  4597. PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer;
  4598. /**
  4599. * Gets a new WebGLBatch from the pool
  4600. *
  4601. * @static
  4602. * @method getBatch
  4603. * @return {WebGLBatch}
  4604. * @private
  4605. */
  4606. PIXI.WebGLRenderer.getBatch = function()
  4607. {
  4608. if(PIXI._batchs.length === 0)
  4609. {
  4610. return new PIXI.WebGLBatch(PIXI.WebGLRenderer.gl);
  4611. }
  4612. else
  4613. {
  4614. return PIXI._batchs.pop();
  4615. }
  4616. }
  4617. /**
  4618. * Puts a batch back into the pool
  4619. *
  4620. * @static
  4621. * @method returnBatch
  4622. * @param batch {WebGLBatch} The batch to return
  4623. * @private
  4624. */
  4625. PIXI.WebGLRenderer.returnBatch = function(batch)
  4626. {
  4627. batch.clean();
  4628. PIXI._batchs.push(batch);
  4629. }
  4630. /**
  4631. * Renders the stage to its webGL view
  4632. *
  4633. * @method render
  4634. * @param stage {Stage} the Stage element to be rendered
  4635. */
  4636. PIXI.WebGLRenderer.prototype.render = function(stage)
  4637. {
  4638. if(this.contextLost)return;
  4639. // if rendering a new stage clear the batchs..
  4640. if(this.__stage !== stage)
  4641. {
  4642. // TODO make this work
  4643. // dont think this is needed any more?
  4644. this.__stage = stage;
  4645. this.stageRenderGroup.setRenderable(stage);
  4646. }
  4647. // update any textures
  4648. PIXI.WebGLRenderer.updateTextures();
  4649. // update the scene graph
  4650. PIXI.visibleCount++;
  4651. stage.updateTransform();
  4652. var gl = this.gl;
  4653. // -- Does this need to be set every frame? -- //
  4654. gl.colorMask(true, true, true, this.transparent);
  4655. gl.viewport(0, 0, this.width, this.height);
  4656. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4657. gl.clearColor(stage.backgroundColorSplit[0],stage.backgroundColorSplit[1],stage.backgroundColorSplit[2], !this.transparent);
  4658. gl.clear(gl.COLOR_BUFFER_BIT);
  4659. // HACK TO TEST
  4660. this.stageRenderGroup.backgroundColor = stage.backgroundColorSplit;
  4661. PIXI.projection.x = this.width/2;
  4662. PIXI.projection.y = -this.height/2;
  4663. this.stageRenderGroup.render(PIXI.projection);
  4664. // interaction
  4665. // run interaction!
  4666. if(stage.interactive)
  4667. {
  4668. //need to add some events!
  4669. if(!stage._interactiveEventsAdded)
  4670. {
  4671. stage._interactiveEventsAdded = true;
  4672. stage.interactionManager.setTarget(this);
  4673. }
  4674. }
  4675. // after rendering lets confirm all frames that have been uodated..
  4676. if(PIXI.Texture.frameUpdates.length > 0)
  4677. {
  4678. for (var i=0; i < PIXI.Texture.frameUpdates.length; i++)
  4679. {
  4680. PIXI.Texture.frameUpdates[i].updateFrame = false;
  4681. };
  4682. PIXI.Texture.frameUpdates = [];
  4683. }
  4684. }
  4685. /**
  4686. * Updates the textures loaded into this webgl renderer
  4687. *
  4688. * @static
  4689. * @method updateTextures
  4690. * @private
  4691. */
  4692. PIXI.WebGLRenderer.updateTextures = function()
  4693. {
  4694. //TODO break this out into a texture manager...
  4695. for (var i=0; i < PIXI.texturesToUpdate.length; i++) PIXI.WebGLRenderer.updateTexture(PIXI.texturesToUpdate[i]);
  4696. for (var i=0; i < PIXI.texturesToDestroy.length; i++) PIXI.WebGLRenderer.destroyTexture(PIXI.texturesToDestroy[i]);
  4697. PIXI.texturesToUpdate = [];
  4698. PIXI.texturesToDestroy = [];
  4699. }
  4700. /**
  4701. * Updates a loaded webgl texture
  4702. *
  4703. * @static
  4704. * @method updateTexture
  4705. * @param texture {Texture} The texture to update
  4706. * @private
  4707. */
  4708. PIXI.WebGLRenderer.updateTexture = function(texture)
  4709. {
  4710. //TODO break this out into a texture manager...
  4711. var gl = PIXI.gl;
  4712. if(!texture._glTexture)
  4713. {
  4714. texture._glTexture = gl.createTexture();
  4715. }
  4716. if(texture.hasLoaded)
  4717. {
  4718. gl.bindTexture(gl.TEXTURE_2D, texture._glTexture);
  4719. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
  4720. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source);
  4721. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4722. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  4723. // reguler...
  4724. if(!texture._powerOf2)
  4725. {
  4726. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4727. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4728. }
  4729. else
  4730. {
  4731. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
  4732. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
  4733. }
  4734. gl.bindTexture(gl.TEXTURE_2D, null);
  4735. }
  4736. }
  4737. /**
  4738. * Destroys a loaded webgl texture
  4739. *
  4740. * @method destroyTexture
  4741. * @param texture {Texture} The texture to update
  4742. * @private
  4743. */
  4744. PIXI.WebGLRenderer.destroyTexture = function(texture)
  4745. {
  4746. //TODO break this out into a texture manager...
  4747. var gl = PIXI.gl;
  4748. if(texture._glTexture)
  4749. {
  4750. texture._glTexture = gl.createTexture();
  4751. gl.deleteTexture(gl.TEXTURE_2D, texture._glTexture);
  4752. }
  4753. }
  4754. /**
  4755. * resizes the webGL view to the specified width and height
  4756. *
  4757. * @method resize
  4758. * @param width {Number} the new width of the webGL view
  4759. * @param height {Number} the new height of the webGL view
  4760. */
  4761. PIXI.WebGLRenderer.prototype.resize = function(width, height)
  4762. {
  4763. this.width = width;
  4764. this.height = height;
  4765. this.view.width = width;
  4766. this.view.height = height;
  4767. this.gl.viewport(0, 0, this.width, this.height);
  4768. //var projectionMatrix = this.projectionMatrix;
  4769. PIXI.projection.x = this.width/2;
  4770. PIXI.projection.y = -this.height/2;
  4771. //PIXI.size.x = this.width/2;
  4772. //PIXI.size.y = -this.height/2;
  4773. // projectionMatrix[0] = 2/this.width;
  4774. // projectionMatrix[5] = -2/this.height;
  4775. // projectionMatrix[12] = -1;
  4776. // projectionMatrix[13] = 1;
  4777. }
  4778. /**
  4779. * Handles a lost webgl context
  4780. *
  4781. * @method handleContextLost
  4782. * @param event {Event}
  4783. * @private
  4784. */
  4785. PIXI.WebGLRenderer.prototype.handleContextLost = function(event)
  4786. {
  4787. event.preventDefault();
  4788. this.contextLost = true;
  4789. }
  4790. /**
  4791. * Handles a restored webgl context
  4792. *
  4793. * @method handleContextRestored
  4794. * @param event {Event}
  4795. * @private
  4796. */
  4797. PIXI.WebGLRenderer.prototype.handleContextRestored = function(event)
  4798. {
  4799. this.gl = this.view.getContext("experimental-webgl", {
  4800. alpha: true
  4801. });
  4802. this.initShaders();
  4803. for(var key in PIXI.TextureCache)
  4804. {
  4805. var texture = PIXI.TextureCache[key].baseTexture;
  4806. texture._glTexture = null;
  4807. PIXI.WebGLRenderer.updateTexture(texture);
  4808. };
  4809. for (var i=0; i < this.batchs.length; i++)
  4810. {
  4811. this.batchs[i].restoreLostContext(this.gl)//
  4812. this.batchs[i].dirty = true;
  4813. };
  4814. PIXI._restoreBatchs(this.gl);
  4815. this.contextLost = false;
  4816. }
  4817. /**
  4818. * @author Mat Groves http://matgroves.com/ @Doormat23
  4819. */
  4820. /**
  4821. * A WebGLBatch Enables a group of sprites to be drawn using the same settings.
  4822. * if a group of sprites all have the same baseTexture and blendMode then they can be
  4823. * grouped into a batch. All the sprites in a batch can then be drawn in one go by the
  4824. * GPU which is hugely efficient. ALL sprites in the webGL renderer are added to a batch
  4825. * even if the batch only contains one sprite. Batching is handled automatically by the
  4826. * webGL renderer. A good tip is: the smaller the number of batchs there are, the faster
  4827. * the webGL renderer will run.
  4828. *
  4829. * @class WebGLBatch
  4830. * @contructor
  4831. * @param gl {WebGLContext} An instance of the webGL context
  4832. */
  4833. PIXI.WebGLRenderGroup = function(gl, transparent)
  4834. {
  4835. this.gl = gl;
  4836. this.root;
  4837. this.backgroundColor;
  4838. this.transparent = transparent == undefined ? true : transparent;
  4839. this.batchs = [];
  4840. this.toRemove = [];
  4841. // console.log(this.transparent)
  4842. this.filterManager = new PIXI.WebGLFilterManager(this.transparent);
  4843. }
  4844. // constructor
  4845. PIXI.WebGLRenderGroup.prototype.constructor = PIXI.WebGLRenderGroup;
  4846. /**
  4847. * Add a display object to the webgl renderer
  4848. *
  4849. * @method setRenderable
  4850. * @param displayObject {DisplayObject}
  4851. * @private
  4852. */
  4853. PIXI.WebGLRenderGroup.prototype.setRenderable = function(displayObject)
  4854. {
  4855. // has this changed??
  4856. if(this.root)this.removeDisplayObjectAndChildren(this.root);
  4857. displayObject.worldVisible = displayObject.visible;
  4858. // soooooo //
  4859. // to check if any batchs exist already??
  4860. // TODO what if its already has an object? should remove it
  4861. this.root = displayObject;
  4862. this.addDisplayObjectAndChildren(displayObject);
  4863. }
  4864. /**
  4865. * Renders the stage to its webgl view
  4866. *
  4867. * @method render
  4868. * @param projection {Object}
  4869. */
  4870. PIXI.WebGLRenderGroup.prototype.render = function(projection, buffer)
  4871. {
  4872. PIXI.WebGLRenderer.updateTextures();
  4873. var gl = this.gl;
  4874. gl.uniform2f(PIXI.defaultShader.projectionVector, projection.x, projection.y);
  4875. this.filterManager.begin(projection, buffer);
  4876. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  4877. // will render all the elements in the group
  4878. var renderable;
  4879. for (var i=0; i < this.batchs.length; i++)
  4880. {
  4881. renderable = this.batchs[i];
  4882. if(renderable instanceof PIXI.WebGLBatch)
  4883. {
  4884. this.batchs[i].render();
  4885. continue;
  4886. }
  4887. // render special
  4888. this.renderSpecial(renderable, projection);
  4889. }
  4890. }
  4891. /**
  4892. * Renders a specific displayObject
  4893. *
  4894. * @method renderSpecific
  4895. * @param displayObject {DisplayObject}
  4896. * @param projection {Object}
  4897. * @private
  4898. */
  4899. PIXI.WebGLRenderGroup.prototype.renderSpecific = function(displayObject, projection, buffer)
  4900. {
  4901. PIXI.WebGLRenderer.updateTextures();
  4902. var gl = this.gl;
  4903. gl.uniform2f(PIXI.defaultShader.projectionVector, projection.x, projection.y);
  4904. this.filterManager.begin(projection, buffer);
  4905. // to do!
  4906. // render part of the scene...
  4907. var startIndex;
  4908. var startBatchIndex;
  4909. var endIndex;
  4910. var endBatchIndex;
  4911. /*
  4912. * LOOK FOR THE NEXT SPRITE
  4913. * This part looks for the closest next sprite that can go into a batch
  4914. * it keeps looking until it finds a sprite or gets to the end of the display
  4915. * scene graph
  4916. */
  4917. var nextRenderable = displayObject.first;
  4918. while(nextRenderable._iNext)
  4919. {
  4920. if(nextRenderable.renderable && nextRenderable.__renderGroup)break;
  4921. nextRenderable = nextRenderable._iNext;
  4922. }
  4923. var startBatch = nextRenderable.batch;
  4924. //console.log(nextRenderable);
  4925. //console.log(renderable)
  4926. if(nextRenderable instanceof PIXI.Sprite)
  4927. {
  4928. startBatch = nextRenderable.batch;
  4929. var head = startBatch.head;
  4930. var next = head;
  4931. // ok now we have the batch.. need to find the start index!
  4932. if(head == nextRenderable)
  4933. {
  4934. startIndex = 0;
  4935. }
  4936. else
  4937. {
  4938. startIndex = 1;
  4939. while(head.__next != nextRenderable)
  4940. {
  4941. startIndex++;
  4942. head = head.__next;
  4943. }
  4944. }
  4945. }
  4946. else
  4947. {
  4948. startBatch = nextRenderable;
  4949. }
  4950. // Get the LAST renderable object
  4951. var lastRenderable = displayObject.last;
  4952. while(lastRenderable._iPrev)
  4953. {
  4954. if(lastRenderable.renderable && lastRenderable.__renderGroup)break;
  4955. lastRenderable = lastRenderable._iNext;
  4956. }
  4957. if(lastRenderable instanceof PIXI.Sprite)
  4958. {
  4959. endBatch = lastRenderable.batch;
  4960. var head = endBatch.head;
  4961. if(head == lastRenderable)
  4962. {
  4963. endIndex = 0;
  4964. }
  4965. else
  4966. {
  4967. endIndex = 1;
  4968. while(head.__next != lastRenderable)
  4969. {
  4970. endIndex++;
  4971. head = head.__next;
  4972. }
  4973. }
  4974. }
  4975. else
  4976. {
  4977. endBatch = lastRenderable;
  4978. }
  4979. //console.log(endBatch);
  4980. // TODO - need to fold this up a bit!
  4981. if(startBatch == endBatch)
  4982. {
  4983. if(startBatch instanceof PIXI.WebGLBatch)
  4984. {
  4985. startBatch.render(startIndex, endIndex+1);
  4986. }
  4987. else
  4988. {
  4989. this.renderSpecial(startBatch, projection);
  4990. }
  4991. return;
  4992. }
  4993. // now we have first and last!
  4994. startBatchIndex = this.batchs.indexOf(startBatch);
  4995. endBatchIndex = this.batchs.indexOf(endBatch);
  4996. // DO the first batch
  4997. if(startBatch instanceof PIXI.WebGLBatch)
  4998. {
  4999. startBatch.render(startIndex);
  5000. }
  5001. else
  5002. {
  5003. this.renderSpecial(startBatch, projection);
  5004. }
  5005. // DO the middle batchs..
  5006. for (var i=startBatchIndex+1; i < endBatchIndex; i++)
  5007. {
  5008. renderable = this.batchs[i];
  5009. if(renderable instanceof PIXI.WebGLBatch)
  5010. {
  5011. this.batchs[i].render();
  5012. }
  5013. else
  5014. {
  5015. this.renderSpecial(renderable, projection);
  5016. }
  5017. }
  5018. // DO the last batch..
  5019. if(endBatch instanceof PIXI.WebGLBatch)
  5020. {
  5021. endBatch.render(0, endIndex+1);
  5022. }
  5023. else
  5024. {
  5025. this.renderSpecial(endBatch, projection);
  5026. }
  5027. }
  5028. /**
  5029. * Renders a specific renderable
  5030. *
  5031. * @method renderSpecial
  5032. * @param renderable {DisplayObject}
  5033. * @param projection {Object}
  5034. * @private
  5035. */
  5036. PIXI.WebGLRenderGroup.prototype.renderSpecial = function(renderable, projection)
  5037. {
  5038. var worldVisible = renderable.vcount === PIXI.visibleCount
  5039. if(renderable instanceof PIXI.TilingSprite)
  5040. {
  5041. if(worldVisible)this.renderTilingSprite(renderable, projection);
  5042. }
  5043. else if(renderable instanceof PIXI.Strip)
  5044. {
  5045. if(worldVisible)this.renderStrip(renderable, projection);
  5046. }
  5047. else if(renderable instanceof PIXI.CustomRenderable)
  5048. {
  5049. if(worldVisible) renderable.renderWebGL(this, projection);
  5050. }
  5051. else if(renderable instanceof PIXI.Graphics)
  5052. {
  5053. if(worldVisible && renderable.renderable) PIXI.WebGLGraphics.renderGraphics(renderable, projection);
  5054. }
  5055. else if(renderable instanceof PIXI.FilterBlock)
  5056. {
  5057. this.handleFilterBlock(renderable, projection);
  5058. }
  5059. }
  5060. flip = false;
  5061. var maskStack = [];
  5062. var maskPosition = 0;
  5063. //var usedMaskStack = [];
  5064. PIXI.WebGLRenderGroup.prototype.handleFilterBlock = function(filterBlock, projection)
  5065. {
  5066. /*
  5067. * for now only masks are supported..
  5068. */
  5069. var gl = PIXI.gl;
  5070. if(filterBlock.open)
  5071. {
  5072. if(filterBlock.data instanceof Array)
  5073. {
  5074. this.filterManager.pushFilter(filterBlock);
  5075. // ok so..
  5076. }
  5077. else
  5078. {
  5079. maskPosition++;
  5080. maskStack.push(filterBlock)
  5081. gl.enable(gl.STENCIL_TEST);
  5082. gl.colorMask(false, false, false, false);
  5083. gl.stencilFunc(gl.ALWAYS,1,1);
  5084. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  5085. PIXI.WebGLGraphics.renderGraphics(filterBlock.data, projection);
  5086. gl.colorMask(true, true, true, true);
  5087. gl.stencilFunc(gl.NOTEQUAL,0,maskStack.length);
  5088. gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
  5089. }
  5090. }
  5091. else
  5092. {
  5093. if(filterBlock.data instanceof Array)
  5094. {
  5095. this.filterManager.popFilter();
  5096. }
  5097. else
  5098. {
  5099. var maskData = maskStack.pop(filterBlock)
  5100. if(maskData)
  5101. {
  5102. gl.colorMask(false, false, false, false);
  5103. gl.stencilFunc(gl.ALWAYS,1,1);
  5104. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  5105. PIXI.WebGLGraphics.renderGraphics(maskData.data, projection);
  5106. gl.colorMask(true, true, true, true);
  5107. gl.stencilFunc(gl.NOTEQUAL,0,maskStack.length);
  5108. gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
  5109. };
  5110. gl.disable(gl.STENCIL_TEST);
  5111. }
  5112. }
  5113. }
  5114. /**
  5115. * Updates a webgl texture
  5116. *
  5117. * @method updateTexture
  5118. * @param displayObject {DisplayObject}
  5119. * @private
  5120. */
  5121. PIXI.WebGLRenderGroup.prototype.updateTexture = function(displayObject)
  5122. {
  5123. // TODO definitely can optimse this function..
  5124. this.removeObject(displayObject);
  5125. /*
  5126. * LOOK FOR THE PREVIOUS RENDERABLE
  5127. * This part looks for the closest previous sprite that can go into a batch
  5128. * It keeps going back until it finds a sprite or the stage
  5129. */
  5130. var previousRenderable = displayObject.first;
  5131. while(previousRenderable != this.root)
  5132. {
  5133. previousRenderable = previousRenderable._iPrev;
  5134. if(previousRenderable.renderable && previousRenderable.__renderGroup)break;
  5135. }
  5136. /*
  5137. * LOOK FOR THE NEXT SPRITE
  5138. * This part looks for the closest next sprite that can go into a batch
  5139. * it keeps looking until it finds a sprite or gets to the end of the display
  5140. * scene graph
  5141. */
  5142. var nextRenderable = displayObject.last;
  5143. while(nextRenderable._iNext)
  5144. {
  5145. nextRenderable = nextRenderable._iNext;
  5146. if(nextRenderable.renderable && nextRenderable.__renderGroup)break;
  5147. }
  5148. this.insertObject(displayObject, previousRenderable, nextRenderable);
  5149. }
  5150. /**
  5151. * Adds filter blocks
  5152. *
  5153. * @method addFilterBlocks
  5154. * @param start {FilterBlock}
  5155. * @param end {FilterBlock}
  5156. * @private
  5157. */
  5158. PIXI.WebGLRenderGroup.prototype.addFilterBlocks = function(start, end)
  5159. {
  5160. start.__renderGroup = this;
  5161. end.__renderGroup = this;
  5162. /*
  5163. * LOOK FOR THE PREVIOUS RENDERABLE
  5164. * This part looks for the closest previous sprite that can go into a batch
  5165. * It keeps going back until it finds a sprite or the stage
  5166. */
  5167. var previousRenderable = start;
  5168. while(previousRenderable != this.root.first)
  5169. {
  5170. previousRenderable = previousRenderable._iPrev;
  5171. if(previousRenderable.renderable && previousRenderable.__renderGroup)break;
  5172. }
  5173. this.insertAfter(start, previousRenderable);
  5174. /*
  5175. * LOOK FOR THE NEXT SPRITE
  5176. * This part looks for the closest next sprite that can go into a batch
  5177. * it keeps looking until it finds a sprite or gets to the end of the display
  5178. * scene graph
  5179. */
  5180. var previousRenderable2 = end;
  5181. while(previousRenderable2 != this.root.first)
  5182. {
  5183. previousRenderable2 = previousRenderable2._iPrev;
  5184. if(previousRenderable2.renderable && previousRenderable2.__renderGroup)break;
  5185. }
  5186. this.insertAfter(end, previousRenderable2);
  5187. }
  5188. /**
  5189. * Remove filter blocks
  5190. *
  5191. * @method removeFilterBlocks
  5192. * @param start {FilterBlock}
  5193. * @param end {FilterBlock}
  5194. * @private
  5195. */
  5196. PIXI.WebGLRenderGroup.prototype.removeFilterBlocks = function(start, end)
  5197. {
  5198. this.removeObject(start);
  5199. this.removeObject(end);
  5200. }
  5201. /**
  5202. * Adds a display object and children to the webgl context
  5203. *
  5204. * @method addDisplayObjectAndChildren
  5205. * @param displayObject {DisplayObject}
  5206. * @private
  5207. */
  5208. PIXI.WebGLRenderGroup.prototype.addDisplayObjectAndChildren = function(displayObject)
  5209. {
  5210. if(displayObject.__renderGroup)displayObject.__renderGroup.removeDisplayObjectAndChildren(displayObject);
  5211. /*
  5212. * LOOK FOR THE PREVIOUS RENDERABLE
  5213. * This part looks for the closest previous sprite that can go into a batch
  5214. * It keeps going back until it finds a sprite or the stage
  5215. */
  5216. var previousRenderable = displayObject.first;
  5217. while(previousRenderable != this.root.first)
  5218. {
  5219. previousRenderable = previousRenderable._iPrev;
  5220. if(previousRenderable.renderable && previousRenderable.__renderGroup)break;
  5221. }
  5222. /*
  5223. * LOOK FOR THE NEXT SPRITE
  5224. * This part looks for the closest next sprite that can go into a batch
  5225. * it keeps looking until it finds a sprite or gets to the end of the display
  5226. * scene graph
  5227. */
  5228. var nextRenderable = displayObject.last;
  5229. while(nextRenderable._iNext)
  5230. {
  5231. nextRenderable = nextRenderable._iNext;
  5232. if(nextRenderable.renderable && nextRenderable.__renderGroup)break;
  5233. }
  5234. // one the display object hits this. we can break the loop
  5235. var tempObject = displayObject.first;
  5236. var testObject = displayObject.last._iNext;
  5237. do
  5238. {
  5239. tempObject.__renderGroup = this;
  5240. if(tempObject.renderable)
  5241. {
  5242. this.insertObject(tempObject, previousRenderable, nextRenderable);
  5243. previousRenderable = tempObject;
  5244. }
  5245. tempObject = tempObject._iNext;
  5246. }
  5247. while(tempObject != testObject)
  5248. }
  5249. /**
  5250. * Removes a display object and children to the webgl context
  5251. *
  5252. * @method removeDisplayObjectAndChildren
  5253. * @param displayObject {DisplayObject}
  5254. * @private
  5255. */
  5256. PIXI.WebGLRenderGroup.prototype.removeDisplayObjectAndChildren = function(displayObject)
  5257. {
  5258. if(displayObject.__renderGroup != this)return;
  5259. // var displayObject = displayObject.first;
  5260. var lastObject = displayObject.last;
  5261. do
  5262. {
  5263. displayObject.__renderGroup = null;
  5264. if(displayObject.renderable)this.removeObject(displayObject);
  5265. displayObject = displayObject._iNext;
  5266. }
  5267. while(displayObject)
  5268. }
  5269. /**
  5270. * Inserts a displayObject into the linked list
  5271. *
  5272. * @method insertObject
  5273. * @param displayObject {DisplayObject}
  5274. * @param previousObject {DisplayObject}
  5275. * @param nextObject {DisplayObject}
  5276. * @private
  5277. */
  5278. PIXI.WebGLRenderGroup.prototype.insertObject = function(displayObject, previousObject, nextObject)
  5279. {
  5280. // while looping below THE OBJECT MAY NOT HAVE BEEN ADDED
  5281. var previousSprite = previousObject;
  5282. var nextSprite = nextObject;
  5283. /*
  5284. * so now we have the next renderable and the previous renderable
  5285. *
  5286. */
  5287. if(displayObject instanceof PIXI.Sprite)
  5288. {
  5289. var previousBatch
  5290. var nextBatch
  5291. if(previousSprite instanceof PIXI.Sprite)
  5292. {
  5293. previousBatch = previousSprite.batch;
  5294. if(previousBatch)
  5295. {
  5296. if(previousBatch.texture == displayObject.texture.baseTexture && previousBatch.blendMode == displayObject.blendMode)
  5297. {
  5298. previousBatch.insertAfter(displayObject, previousSprite);
  5299. return;
  5300. }
  5301. }
  5302. }
  5303. else
  5304. {
  5305. // TODO reword!
  5306. previousBatch = previousSprite;
  5307. }
  5308. if(nextSprite)
  5309. {
  5310. if(nextSprite instanceof PIXI.Sprite)
  5311. {
  5312. nextBatch = nextSprite.batch;
  5313. //batch may not exist if item was added to the display list but not to the webGL
  5314. if(nextBatch)
  5315. {
  5316. if(nextBatch.texture == displayObject.texture.baseTexture && nextBatch.blendMode == displayObject.blendMode)
  5317. {
  5318. nextBatch.insertBefore(displayObject, nextSprite);
  5319. return;
  5320. }
  5321. else
  5322. {
  5323. if(nextBatch == previousBatch)
  5324. {
  5325. // THERE IS A SPLIT IN THIS BATCH! //
  5326. var splitBatch = previousBatch.split(nextSprite);
  5327. // COOL!
  5328. // add it back into the array
  5329. /*
  5330. * OOPS!
  5331. * seems the new sprite is in the middle of a batch
  5332. * lets split it..
  5333. */
  5334. var batch = PIXI.WebGLRenderer.getBatch();
  5335. var index = this.batchs.indexOf( previousBatch );
  5336. batch.init(displayObject);
  5337. this.batchs.splice(index+1, 0, batch, splitBatch);
  5338. return;
  5339. }
  5340. }
  5341. }
  5342. }
  5343. else
  5344. {
  5345. // TODO re-word!
  5346. nextBatch = nextSprite;
  5347. }
  5348. }
  5349. /*
  5350. * looks like it does not belong to any batch!
  5351. * but is also not intersecting one..
  5352. * time to create anew one!
  5353. */
  5354. var batch = PIXI.WebGLRenderer.getBatch();
  5355. batch.init(displayObject);
  5356. if(previousBatch) // if this is invalid it means
  5357. {
  5358. var index = this.batchs.indexOf( previousBatch );
  5359. this.batchs.splice(index+1, 0, batch);
  5360. }
  5361. else
  5362. {
  5363. this.batchs.push(batch);
  5364. }
  5365. return;
  5366. }
  5367. else if(displayObject instanceof PIXI.TilingSprite)
  5368. {
  5369. // add to a batch!!
  5370. this.initTilingSprite(displayObject);
  5371. // this.batchs.push(displayObject);
  5372. }
  5373. else if(displayObject instanceof PIXI.Strip)
  5374. {
  5375. // add to a batch!!
  5376. this.initStrip(displayObject);
  5377. // this.batchs.push(displayObject);
  5378. }
  5379. else if(displayObject)// instanceof PIXI.Graphics)
  5380. {
  5381. //displayObject.initWebGL(this);
  5382. // add to a batch!!
  5383. //this.initStrip(displayObject);
  5384. //this.batchs.push(displayObject);
  5385. }
  5386. this.insertAfter(displayObject, previousSprite);
  5387. // insert and SPLIT!
  5388. }
  5389. /**
  5390. * Inserts a displayObject into the linked list
  5391. *
  5392. * @method insertAfter
  5393. * @param item {DisplayObject}
  5394. * @param displayObject {DisplayObject} The object to insert
  5395. * @private
  5396. */
  5397. PIXI.WebGLRenderGroup.prototype.insertAfter = function(item, displayObject)
  5398. {
  5399. if(displayObject instanceof PIXI.Sprite)
  5400. {
  5401. var previousBatch = displayObject.batch;
  5402. if(previousBatch)
  5403. {
  5404. // so this object is in a batch!
  5405. // is it not? need to split the batch
  5406. if(previousBatch.tail == displayObject)
  5407. {
  5408. // is it tail? insert in to batchs
  5409. var index = this.batchs.indexOf( previousBatch );
  5410. this.batchs.splice(index+1, 0, item);
  5411. }
  5412. else
  5413. {
  5414. // TODO MODIFY ADD / REMOVE CHILD TO ACCOUNT FOR FILTERS (also get prev and next) //
  5415. // THERE IS A SPLIT IN THIS BATCH! //
  5416. var splitBatch = previousBatch.split(displayObject.__next);
  5417. // COOL!
  5418. // add it back into the array
  5419. /*
  5420. * OOPS!
  5421. * seems the new sprite is in the middle of a batch
  5422. * lets split it..
  5423. */
  5424. var index = this.batchs.indexOf( previousBatch );
  5425. this.batchs.splice(index+1, 0, item, splitBatch);
  5426. }
  5427. }
  5428. else
  5429. {
  5430. this.batchs.push(item);
  5431. }
  5432. }
  5433. else
  5434. {
  5435. var index = this.batchs.indexOf( displayObject );
  5436. this.batchs.splice(index+1, 0, item);
  5437. }
  5438. }
  5439. /**
  5440. * Removes a displayObject from the linked list
  5441. *
  5442. * @method removeObject
  5443. * @param displayObject {DisplayObject} The object to remove
  5444. * @private
  5445. */
  5446. PIXI.WebGLRenderGroup.prototype.removeObject = function(displayObject)
  5447. {
  5448. // loop through children..
  5449. // display object //
  5450. // add a child from the render group..
  5451. // remove it and all its children!
  5452. //displayObject.cacheVisible = false;//displayObject.visible;
  5453. /*
  5454. * removing is a lot quicker..
  5455. *
  5456. */
  5457. var batchToRemove;
  5458. if(displayObject instanceof PIXI.Sprite)
  5459. {
  5460. // should always have a batch!
  5461. var batch = displayObject.batch;
  5462. if(!batch)return; // this means the display list has been altered befre rendering
  5463. batch.remove(displayObject);
  5464. if(batch.size==0)
  5465. {
  5466. batchToRemove = batch;
  5467. }
  5468. }
  5469. else
  5470. {
  5471. batchToRemove = displayObject;
  5472. }
  5473. /*
  5474. * Looks like there is somthing that needs removing!
  5475. */
  5476. if(batchToRemove)
  5477. {
  5478. var index = this.batchs.indexOf( batchToRemove );
  5479. if(index == -1)return;// this means it was added then removed before rendered
  5480. // ok so.. check to see if you adjacent batchs should be joined.
  5481. // TODO may optimise?
  5482. if(index === 0 || index == this.batchs.length-1)
  5483. {
  5484. // wha - eva! just get of the empty batch!
  5485. this.batchs.splice(index, 1);
  5486. if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove);
  5487. return;
  5488. }
  5489. if(this.batchs[index-1] instanceof PIXI.WebGLBatch && this.batchs[index+1] instanceof PIXI.WebGLBatch)
  5490. {
  5491. if(this.batchs[index-1].texture == this.batchs[index+1].texture && this.batchs[index-1].blendMode == this.batchs[index+1].blendMode)
  5492. {
  5493. //console.log("MERGE")
  5494. this.batchs[index-1].merge(this.batchs[index+1]);
  5495. if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove);
  5496. PIXI.WebGLRenderer.returnBatch(this.batchs[index+1]);
  5497. this.batchs.splice(index, 2);
  5498. return;
  5499. }
  5500. }
  5501. this.batchs.splice(index, 1);
  5502. if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove);
  5503. }
  5504. }
  5505. /**
  5506. * Initializes a tiling sprite
  5507. *
  5508. * @method initTilingSprite
  5509. * @param sprite {TilingSprite} The tiling sprite to initialize
  5510. * @private
  5511. */
  5512. PIXI.WebGLRenderGroup.prototype.initTilingSprite = function(sprite)
  5513. {
  5514. var gl = this.gl;
  5515. // make the texture tilable..
  5516. sprite.verticies = new Float32Array([0, 0,
  5517. sprite.width, 0,
  5518. sprite.width, sprite.height,
  5519. 0, sprite.height]);
  5520. sprite.uvs = new Float32Array([0, 0,
  5521. 1, 0,
  5522. 1, 1,
  5523. 0, 1]);
  5524. sprite.colors = new Float32Array([1,1,1,1]);
  5525. sprite.indices = new Uint16Array([0, 1, 3,2])//, 2]);
  5526. sprite._vertexBuffer = gl.createBuffer();
  5527. sprite._indexBuffer = gl.createBuffer();
  5528. sprite._uvBuffer = gl.createBuffer();
  5529. sprite._colorBuffer = gl.createBuffer();
  5530. gl.bindBuffer(gl.ARRAY_BUFFER, sprite._vertexBuffer);
  5531. gl.bufferData(gl.ARRAY_BUFFER, sprite.verticies, gl.STATIC_DRAW);
  5532. gl.bindBuffer(gl.ARRAY_BUFFER, sprite._uvBuffer);
  5533. gl.bufferData(gl.ARRAY_BUFFER, sprite.uvs, gl.DYNAMIC_DRAW);
  5534. gl.bindBuffer(gl.ARRAY_BUFFER, sprite._colorBuffer);
  5535. gl.bufferData(gl.ARRAY_BUFFER, sprite.colors, gl.STATIC_DRAW);
  5536. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, sprite._indexBuffer);
  5537. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, sprite.indices, gl.STATIC_DRAW);
  5538. // return ( (x > 0) && ((x & (x - 1)) === 0) );
  5539. if(sprite.texture.baseTexture._glTexture)
  5540. {
  5541. gl.bindTexture(gl.TEXTURE_2D, sprite.texture.baseTexture._glTexture);
  5542. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
  5543. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
  5544. sprite.texture.baseTexture._powerOf2 = true;
  5545. }
  5546. else
  5547. {
  5548. sprite.texture.baseTexture._powerOf2 = true;
  5549. }
  5550. }
  5551. /**
  5552. * Renders a Strip
  5553. *
  5554. * @method renderStrip
  5555. * @param strip {Strip} The strip to render
  5556. * @param projection {Object}
  5557. * @private
  5558. */
  5559. PIXI.WebGLRenderGroup.prototype.renderStrip = function(strip, projection)
  5560. {
  5561. var gl = this.gl;
  5562. PIXI.activateStripShader();
  5563. var shader = PIXI.stripShader;
  5564. var program = shader.program;
  5565. var m = PIXI.mat3.clone(strip.worldTransform);
  5566. PIXI.mat3.transpose(m);
  5567. // console.log(projection)
  5568. // set the matrix transform for the
  5569. gl.uniformMatrix3fv(shader.translationMatrix, false, m);
  5570. gl.uniform2f(shader.projectionVector, projection.x, projection.y);
  5571. gl.uniform2f(shader.offsetVector, -PIXI.offset.x, -PIXI.offset.y);
  5572. gl.uniform1f(shader.alpha, strip.worldAlpha);
  5573. /*
  5574. if(strip.blendMode == PIXI.blendModes.NORMAL)
  5575. {
  5576. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5577. }
  5578. else
  5579. {
  5580. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR);
  5581. }
  5582. */
  5583. //console.log("!!")
  5584. if(!strip.dirty)
  5585. {
  5586. gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer);
  5587. gl.bufferSubData(gl.ARRAY_BUFFER, 0, strip.verticies)
  5588. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  5589. // update the uvs
  5590. gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer);
  5591. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  5592. gl.activeTexture(gl.TEXTURE0);
  5593. gl.bindTexture(gl.TEXTURE_2D, strip.texture.baseTexture._glTexture);
  5594. gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer);
  5595. gl.vertexAttribPointer(shader.colorAttribute, 1, gl.FLOAT, false, 0, 0);
  5596. // dont need to upload!
  5597. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer);
  5598. }
  5599. else
  5600. {
  5601. strip.dirty = false;
  5602. gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer);
  5603. gl.bufferData(gl.ARRAY_BUFFER, strip.verticies, gl.STATIC_DRAW)
  5604. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  5605. // update the uvs
  5606. gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer);
  5607. gl.bufferData(gl.ARRAY_BUFFER, strip.uvs, gl.STATIC_DRAW)
  5608. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  5609. gl.activeTexture(gl.TEXTURE0);
  5610. gl.bindTexture(gl.TEXTURE_2D, strip.texture.baseTexture._glTexture);
  5611. // console.log(strip.texture.baseTexture._glTexture)
  5612. gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer);
  5613. gl.bufferData(gl.ARRAY_BUFFER, strip.colors, gl.STATIC_DRAW)
  5614. gl.vertexAttribPointer(shader.colorAttribute, 1, gl.FLOAT, false, 0, 0);
  5615. // dont need to upload!
  5616. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer);
  5617. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, strip.indices, gl.STATIC_DRAW);
  5618. }
  5619. gl.drawElements(gl.TRIANGLE_STRIP, strip.indices.length, gl.UNSIGNED_SHORT, 0);
  5620. PIXI.deactivateStripShader();
  5621. //gl.useProgram(PIXI.currentProgram);
  5622. }
  5623. /**
  5624. * Renders a TilingSprite
  5625. *
  5626. * @method renderTilingSprite
  5627. * @param sprite {TilingSprite} The tiling sprite to render
  5628. * @param projectionMatrix {Object}
  5629. * @private
  5630. */
  5631. PIXI.WebGLRenderGroup.prototype.renderTilingSprite = function(sprite, projectionMatrix)
  5632. {
  5633. var gl = this.gl;
  5634. var shaderProgram = PIXI.shaderProgram;
  5635. var tilePosition = sprite.tilePosition;
  5636. var tileScale = sprite.tileScale;
  5637. var offsetX = tilePosition.x/sprite.texture.baseTexture.width;
  5638. var offsetY = tilePosition.y/sprite.texture.baseTexture.height;
  5639. var scaleX = (sprite.width / sprite.texture.baseTexture.width) / tileScale.x;
  5640. var scaleY = (sprite.height / sprite.texture.baseTexture.height) / tileScale.y;
  5641. sprite.uvs[0] = 0 - offsetX;
  5642. sprite.uvs[1] = 0 - offsetY;
  5643. sprite.uvs[2] = (1 * scaleX) -offsetX;
  5644. sprite.uvs[3] = 0 - offsetY;
  5645. sprite.uvs[4] = (1 *scaleX) - offsetX;
  5646. sprite.uvs[5] = (1 *scaleY) - offsetY;
  5647. sprite.uvs[6] = 0 - offsetX;
  5648. sprite.uvs[7] = (1 *scaleY) - offsetY;
  5649. gl.bindBuffer(gl.ARRAY_BUFFER, sprite._uvBuffer);
  5650. gl.bufferSubData(gl.ARRAY_BUFFER, 0, sprite.uvs)
  5651. this.renderStrip(sprite, projectionMatrix);
  5652. }
  5653. /**
  5654. * Initializes a strip to be rendered
  5655. *
  5656. * @method initStrip
  5657. * @param strip {Strip} The strip to initialize
  5658. * @private
  5659. */
  5660. PIXI.WebGLRenderGroup.prototype.initStrip = function(strip)
  5661. {
  5662. // build the strip!
  5663. var gl = this.gl;
  5664. var shaderProgram = this.shaderProgram;
  5665. strip._vertexBuffer = gl.createBuffer();
  5666. strip._indexBuffer = gl.createBuffer();
  5667. strip._uvBuffer = gl.createBuffer();
  5668. strip._colorBuffer = gl.createBuffer();
  5669. gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer);
  5670. gl.bufferData(gl.ARRAY_BUFFER, strip.verticies, gl.DYNAMIC_DRAW);
  5671. gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer);
  5672. gl.bufferData(gl.ARRAY_BUFFER, strip.uvs, gl.STATIC_DRAW);
  5673. gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer);
  5674. gl.bufferData(gl.ARRAY_BUFFER, strip.colors, gl.STATIC_DRAW);
  5675. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer);
  5676. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, strip.indices, gl.STATIC_DRAW);
  5677. }
  5678. /**
  5679. * @author Mat Groves http://matgroves.com/ @Doormat23
  5680. */
  5681. PIXI.initDefaultShaders = function()
  5682. {
  5683. PIXI.primitiveShader = new PIXI.PrimitiveShader();
  5684. PIXI.primitiveShader.init();
  5685. PIXI.stripShader = new PIXI.StripShader();
  5686. PIXI.stripShader.init();
  5687. PIXI.defaultShader = new PIXI.PixiShader();
  5688. PIXI.defaultShader.init();
  5689. var gl = PIXI.gl;
  5690. var shaderProgram = PIXI.defaultShader.program;
  5691. gl.useProgram(shaderProgram);
  5692. gl.enableVertexAttribArray(PIXI.defaultShader.aVertexPosition);
  5693. gl.enableVertexAttribArray(PIXI.defaultShader.colorAttribute);
  5694. gl.enableVertexAttribArray(PIXI.defaultShader.aTextureCoord);
  5695. }
  5696. PIXI.activatePrimitiveShader = function()
  5697. {
  5698. var gl = PIXI.gl;
  5699. gl.useProgram(PIXI.primitiveShader.program);
  5700. gl.disableVertexAttribArray(PIXI.defaultShader.aVertexPosition);
  5701. gl.disableVertexAttribArray(PIXI.defaultShader.colorAttribute);
  5702. gl.disableVertexAttribArray(PIXI.defaultShader.aTextureCoord);
  5703. gl.enableVertexAttribArray(PIXI.primitiveShader.aVertexPosition);
  5704. gl.enableVertexAttribArray(PIXI.primitiveShader.colorAttribute);
  5705. }
  5706. PIXI.deactivatePrimitiveShader = function()
  5707. {
  5708. var gl = PIXI.gl;
  5709. gl.useProgram(PIXI.defaultShader.program);
  5710. gl.disableVertexAttribArray(PIXI.primitiveShader.aVertexPosition);
  5711. gl.disableVertexAttribArray(PIXI.primitiveShader.colorAttribute);
  5712. gl.enableVertexAttribArray(PIXI.defaultShader.aVertexPosition);
  5713. gl.enableVertexAttribArray(PIXI.defaultShader.colorAttribute);
  5714. gl.enableVertexAttribArray(PIXI.defaultShader.aTextureCoord);
  5715. }
  5716. PIXI.activateStripShader = function()
  5717. {
  5718. var gl = PIXI.gl;
  5719. gl.useProgram(PIXI.stripShader.program);
  5720. // gl.disableVertexAttribArray(PIXI.defaultShader.aTextureCoord);
  5721. }
  5722. PIXI.deactivateStripShader = function()
  5723. {
  5724. var gl = PIXI.gl;
  5725. gl.useProgram(PIXI.defaultShader.program);
  5726. //gl.enableVertexAttribArray(PIXI.defaultShader.aTextureCoord);
  5727. }
  5728. /*
  5729. SHADER COMPILER HELPERS
  5730. */
  5731. PIXI.CompileVertexShader = function(gl, shaderSrc)
  5732. {
  5733. return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER);
  5734. }
  5735. PIXI.CompileFragmentShader = function(gl, shaderSrc)
  5736. {
  5737. return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER);
  5738. }
  5739. PIXI._CompileShader = function(gl, shaderSrc, shaderType)
  5740. {
  5741. var src = shaderSrc.join("\n");
  5742. var shader = gl.createShader(shaderType);
  5743. gl.shaderSource(shader, src);
  5744. gl.compileShader(shader);
  5745. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5746. console.log(gl.getShaderInfoLog(shader));
  5747. return null;
  5748. }
  5749. return shader;
  5750. }
  5751. PIXI.compileProgram = function(vertexSrc, fragmentSrc)
  5752. {
  5753. var gl = PIXI.gl;
  5754. var fragmentShader = PIXI.CompileFragmentShader(gl, fragmentSrc);
  5755. var vertexShader = PIXI.CompileVertexShader(gl, vertexSrc);
  5756. var shaderProgram = gl.createProgram();
  5757. gl.attachShader(shaderProgram, vertexShader);
  5758. gl.attachShader(shaderProgram, fragmentShader);
  5759. gl.linkProgram(shaderProgram);
  5760. if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
  5761. console.log("Could not initialise shaders");
  5762. }
  5763. return shaderProgram;
  5764. }
  5765. /**
  5766. * @author Mat Groves http://matgroves.com/ @Doormat23
  5767. */
  5768. /**
  5769. * A Text Object will create a line(s) of text using bitmap font. To split a line you can use "\n", "\r" or "\r\n"
  5770. * You can generate the fnt files using
  5771. * http://www.angelcode.com/products/bmfont/ for windows or
  5772. * http://www.bmglyph.com/ for mac.
  5773. *
  5774. * @class BitmapText
  5775. * @extends DisplayObjectContainer
  5776. * @constructor
  5777. * @param text {String} The copy that you would like the text to display
  5778. * @param style {Object} The style parameters
  5779. * @param style.font {String} The size (optional) and bitmap font id (required) eq "Arial" or "20px Arial" (must have loaded previously)
  5780. * @param [style.align="left"] {String} An alignment of the multiline text ("left", "center" or "right")
  5781. */
  5782. PIXI.BitmapText = function(text, style)
  5783. {
  5784. PIXI.DisplayObjectContainer.call(this);
  5785. this.setText(text);
  5786. this.setStyle(style);
  5787. this.updateText();
  5788. this.dirty = false
  5789. };
  5790. // constructor
  5791. PIXI.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  5792. PIXI.BitmapText.prototype.constructor = PIXI.BitmapText;
  5793. /**
  5794. * Set the copy for the text object
  5795. *
  5796. * @method setText
  5797. * @param text {String} The copy that you would like the text to display
  5798. */
  5799. PIXI.BitmapText.prototype.setText = function(text)
  5800. {
  5801. this.text = text || " ";
  5802. this.dirty = true;
  5803. };
  5804. /**
  5805. * Set the style of the text
  5806. *
  5807. * @method setStyle
  5808. * @param style {Object} The style parameters
  5809. * @param style.font {String} The size (optional) and bitmap font id (required) eq "Arial" or "20px Arial" (must have loaded previously)
  5810. * @param [style.align="left"] {String} An alignment of the multiline text ("left", "center" or "right")
  5811. */
  5812. PIXI.BitmapText.prototype.setStyle = function(style)
  5813. {
  5814. style = style || {};
  5815. style.align = style.align || "left";
  5816. this.style = style;
  5817. var font = style.font.split(" ");
  5818. this.fontName = font[font.length - 1];
  5819. this.fontSize = font.length >= 2 ? parseInt(font[font.length - 2], 10) : PIXI.BitmapText.fonts[this.fontName].size;
  5820. this.dirty = true;
  5821. };
  5822. /**
  5823. * Renders text
  5824. *
  5825. * @method updateText
  5826. * @private
  5827. */
  5828. PIXI.BitmapText.prototype.updateText = function()
  5829. {
  5830. var data = PIXI.BitmapText.fonts[this.fontName];
  5831. var pos = new PIXI.Point();
  5832. var prevCharCode = null;
  5833. var chars = [];
  5834. var maxLineWidth = 0;
  5835. var lineWidths = [];
  5836. var line = 0;
  5837. var scale = this.fontSize / data.size;
  5838. for(var i = 0; i < this.text.length; i++)
  5839. {
  5840. var charCode = this.text.charCodeAt(i);
  5841. if(/(?:\r\n|\r|\n)/.test(this.text.charAt(i)))
  5842. {
  5843. lineWidths.push(pos.x);
  5844. maxLineWidth = Math.max(maxLineWidth, pos.x);
  5845. line++;
  5846. pos.x = 0;
  5847. pos.y += data.lineHeight;
  5848. prevCharCode = null;
  5849. continue;
  5850. }
  5851. var charData = data.chars[charCode];
  5852. if(!charData) continue;
  5853. if(prevCharCode && charData[prevCharCode])
  5854. {
  5855. pos.x += charData.kerning[prevCharCode];
  5856. }
  5857. chars.push({texture:charData.texture, line: line, charCode: charCode, position: new PIXI.Point(pos.x + charData.xOffset, pos.y + charData.yOffset)});
  5858. pos.x += charData.xAdvance;
  5859. prevCharCode = charCode;
  5860. }
  5861. lineWidths.push(pos.x);
  5862. maxLineWidth = Math.max(maxLineWidth, pos.x);
  5863. var lineAlignOffsets = [];
  5864. for(i = 0; i <= line; i++)
  5865. {
  5866. var alignOffset = 0;
  5867. if(this.style.align == "right")
  5868. {
  5869. alignOffset = maxLineWidth - lineWidths[i];
  5870. }
  5871. else if(this.style.align == "center")
  5872. {
  5873. alignOffset = (maxLineWidth - lineWidths[i]) / 2;
  5874. }
  5875. lineAlignOffsets.push(alignOffset);
  5876. }
  5877. for(i = 0; i < chars.length; i++)
  5878. {
  5879. var c = new PIXI.Sprite(chars[i].texture)//PIXI.Sprite.fromFrame(chars[i].charCode);
  5880. c.position.x = (chars[i].position.x + lineAlignOffsets[chars[i].line]) * scale;
  5881. c.position.y = chars[i].position.y * scale;
  5882. c.scale.x = c.scale.y = scale;
  5883. this.addChild(c);
  5884. }
  5885. this.width = pos.x * scale;
  5886. this.height = (pos.y + data.lineHeight) * scale;
  5887. };
  5888. /**
  5889. * Updates the transfor of this object
  5890. *
  5891. * @method updateTransform
  5892. * @private
  5893. */
  5894. PIXI.BitmapText.prototype.updateTransform = function()
  5895. {
  5896. if(this.dirty)
  5897. {
  5898. while(this.children.length > 0)
  5899. {
  5900. this.removeChild(this.getChildAt(0));
  5901. }
  5902. this.updateText();
  5903. this.dirty = false;
  5904. }
  5905. PIXI.DisplayObjectContainer.prototype.updateTransform.call(this);
  5906. };
  5907. PIXI.BitmapText.fonts = {};
  5908. /**
  5909. * @author Mat Groves http://matgroves.com/ @Doormat23
  5910. */
  5911. /**
  5912. * A Text Object will create a line(s) of text to split a line you can use "\n"
  5913. *
  5914. * @class Text
  5915. * @extends Sprite
  5916. * @constructor
  5917. * @param text {String} The copy that you would like the text to display
  5918. * @param [style] {Object} The style parameters
  5919. * @param [style.font] {String} default "bold 20pt Arial" The style and size of the font
  5920. * @param [style.fill="black"] {Object} A canvas fillstyle that will be used on the text eg "red", "#00FF00"
  5921. * @param [style.align="left"] {String} An alignment of the multiline text ("left", "center" or "right")
  5922. * @param [style.stroke] {String} A canvas fillstyle that will be used on the text stroke eg "blue", "#FCFF00"
  5923. * @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke)
  5924. * @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used
  5925. * @param [style.wordWrapWidth=100] {Number} The width at which text will wrap
  5926. */
  5927. PIXI.Text = function(text, style)
  5928. {
  5929. this.canvas = document.createElement("canvas");
  5930. this.context = this.canvas.getContext("2d");
  5931. PIXI.Sprite.call(this, PIXI.Texture.fromCanvas(this.canvas));
  5932. this.setText(text);
  5933. this.setStyle(style);
  5934. this.updateText();
  5935. this.dirty = false;
  5936. };
  5937. // constructor
  5938. PIXI.Text.prototype = Object.create(PIXI.Sprite.prototype);
  5939. PIXI.Text.prototype.constructor = PIXI.Text;
  5940. /**
  5941. * Set the style of the text
  5942. *
  5943. * @method setStyle
  5944. * @param [style] {Object} The style parameters
  5945. * @param [style.font="bold 20pt Arial"] {String} The style and size of the font
  5946. * @param [style.fill="black"] {Object} A canvas fillstyle that will be used on the text eg "red", "#00FF00"
  5947. * @param [style.align="left"] {String} An alignment of the multiline text ("left", "center" or "right")
  5948. * @param [style.stroke="black"] {String} A canvas fillstyle that will be used on the text stroke eg "blue", "#FCFF00"
  5949. * @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke)
  5950. * @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used
  5951. * @param [style.wordWrapWidth=100] {Number} The width at which text will wrap
  5952. */
  5953. PIXI.Text.prototype.setStyle = function(style)
  5954. {
  5955. style = style || {};
  5956. style.font = style.font || "bold 20pt Arial";
  5957. style.fill = style.fill || "black";
  5958. style.align = style.align || "left";
  5959. style.stroke = style.stroke || "black"; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136
  5960. style.strokeThickness = style.strokeThickness || 0;
  5961. style.wordWrap = style.wordWrap || false;
  5962. style.wordWrapWidth = style.wordWrapWidth || 100;
  5963. this.style = style;
  5964. this.dirty = true;
  5965. };
  5966. /**
  5967. * Set the copy for the text object. To split a line you can use "\n"
  5968. *
  5969. * @methos setText
  5970. * @param {String} text The copy that you would like the text to display
  5971. */
  5972. PIXI.Text.prototype.setText = function(text)
  5973. {
  5974. this.text = text.toString() || " ";
  5975. this.dirty = true;
  5976. };
  5977. /**
  5978. * Renders text
  5979. *
  5980. * @method updateText
  5981. * @private
  5982. */
  5983. PIXI.Text.prototype.updateText = function()
  5984. {
  5985. this.context.font = this.style.font;
  5986. var outputText = this.text;
  5987. // word wrap
  5988. // preserve original text
  5989. if(this.style.wordWrap)outputText = this.wordWrap(this.text);
  5990. //split text into lines
  5991. var lines = outputText.split(/(?:\r\n|\r|\n)/);
  5992. //calculate text width
  5993. var lineWidths = [];
  5994. var maxLineWidth = 0;
  5995. for (var i = 0; i < lines.length; i++)
  5996. {
  5997. var lineWidth = this.context.measureText(lines[i]).width;
  5998. lineWidths[i] = lineWidth;
  5999. maxLineWidth = Math.max(maxLineWidth, lineWidth);
  6000. }
  6001. this.canvas.width = maxLineWidth + this.style.strokeThickness;
  6002. //calculate text height
  6003. var lineHeight = this.determineFontHeight("font: " + this.style.font + ";") + this.style.strokeThickness;
  6004. this.canvas.height = lineHeight * lines.length;
  6005. //set canvas text styles
  6006. this.context.fillStyle = this.style.fill;
  6007. this.context.font = this.style.font;
  6008. this.context.strokeStyle = this.style.stroke;
  6009. this.context.lineWidth = this.style.strokeThickness;
  6010. this.context.textBaseline = "top";
  6011. //draw lines line by line
  6012. for (i = 0; i < lines.length; i++)
  6013. {
  6014. var linePosition = new PIXI.Point(this.style.strokeThickness / 2, this.style.strokeThickness / 2 + i * lineHeight);
  6015. if(this.style.align == "right")
  6016. {
  6017. linePosition.x += maxLineWidth - lineWidths[i];
  6018. }
  6019. else if(this.style.align == "center")
  6020. {
  6021. linePosition.x += (maxLineWidth - lineWidths[i]) / 2;
  6022. }
  6023. if(this.style.stroke && this.style.strokeThickness)
  6024. {
  6025. this.context.strokeText(lines[i], linePosition.x, linePosition.y);
  6026. }
  6027. if(this.style.fill)
  6028. {
  6029. this.context.fillText(lines[i], linePosition.x, linePosition.y);
  6030. }
  6031. }
  6032. this.updateTexture();
  6033. };
  6034. /**
  6035. * Updates texture size based on canvas size
  6036. *
  6037. * @method updateTexture
  6038. * @private
  6039. */
  6040. PIXI.Text.prototype.updateTexture = function()
  6041. {
  6042. this.texture.baseTexture.width = this.canvas.width;
  6043. this.texture.baseTexture.height = this.canvas.height;
  6044. this.texture.frame.width = this.canvas.width;
  6045. this.texture.frame.height = this.canvas.height;
  6046. this._width = this.canvas.width;
  6047. this._height = this.canvas.height;
  6048. PIXI.texturesToUpdate.push(this.texture.baseTexture);
  6049. };
  6050. /**
  6051. * Updates the transfor of this object
  6052. *
  6053. * @method updateTransform
  6054. * @private
  6055. */
  6056. PIXI.Text.prototype.updateTransform = function()
  6057. {
  6058. if(this.dirty)
  6059. {
  6060. this.updateText();
  6061. this.dirty = false;
  6062. }
  6063. PIXI.Sprite.prototype.updateTransform.call(this);
  6064. };
  6065. /*
  6066. * http://stackoverflow.com/users/34441/ellisbben
  6067. * great solution to the problem!
  6068. *
  6069. * @method determineFontHeight
  6070. * @param fontStyle {Object}
  6071. * @private
  6072. */
  6073. PIXI.Text.prototype.determineFontHeight = function(fontStyle)
  6074. {
  6075. // build a little reference dictionary so if the font style has been used return a
  6076. // cached version...
  6077. var result = PIXI.Text.heightCache[fontStyle];
  6078. if(!result)
  6079. {
  6080. var body = document.getElementsByTagName("body")[0];
  6081. var dummy = document.createElement("div");
  6082. var dummyText = document.createTextNode("M");
  6083. dummy.appendChild(dummyText);
  6084. dummy.setAttribute("style", fontStyle + ';position:absolute;top:0;left:0');
  6085. body.appendChild(dummy);
  6086. result = dummy.offsetHeight;
  6087. PIXI.Text.heightCache[fontStyle] = result;
  6088. body.removeChild(dummy);
  6089. }
  6090. return result;
  6091. };
  6092. /**
  6093. * Applies newlines to a string to have it optimally fit into the horizontal
  6094. * bounds set by the Text object's wordWrapWidth property.
  6095. *
  6096. * @method wordWrap
  6097. * @param text {String}
  6098. * @private
  6099. */
  6100. PIXI.Text.prototype.wordWrap = function(text)
  6101. {
  6102. // Greedy wrapping algorithm that will wrap words as the line grows longer
  6103. // than its horizontal bounds.
  6104. var result = "";
  6105. var lines = text.split("\n");
  6106. for (var i = 0; i < lines.length; i++)
  6107. {
  6108. var spaceLeft = this.style.wordWrapWidth;
  6109. var words = lines[i].split(" ");
  6110. for (var j = 0; j < words.length; j++)
  6111. {
  6112. var wordWidth = this.context.measureText(words[j]).width;
  6113. var wordWidthWithSpace = wordWidth + this.context.measureText(" ").width;
  6114. if(wordWidthWithSpace > spaceLeft)
  6115. {
  6116. // Skip printing the newline if it's the first word of the line that is
  6117. // greater than the word wrap width.
  6118. if(j > 0)
  6119. {
  6120. result += "\n";
  6121. }
  6122. result += words[j] + " ";
  6123. spaceLeft = this.style.wordWrapWidth - wordWidth;
  6124. }
  6125. else
  6126. {
  6127. spaceLeft -= wordWidthWithSpace;
  6128. result += words[j] + " ";
  6129. }
  6130. }
  6131. result += "\n";
  6132. }
  6133. return result;
  6134. };
  6135. /**
  6136. * Destroys this text object
  6137. *
  6138. * @method destroy
  6139. * @param destroyTexture {Boolean}
  6140. */
  6141. PIXI.Text.prototype.destroy = function(destroyTexture)
  6142. {
  6143. if(destroyTexture)
  6144. {
  6145. this.texture.destroy();
  6146. }
  6147. };
  6148. PIXI.Text.heightCache = {};
  6149. /**
  6150. * @author Mat Groves http://matgroves.com/ @Doormat23
  6151. */
  6152. PIXI.BaseTextureCache = {};
  6153. PIXI.texturesToUpdate = [];
  6154. PIXI.texturesToDestroy = [];
  6155. /**
  6156. * A texture stores the information that represents an image. All textures have a base texture
  6157. *
  6158. * @class BaseTexture
  6159. * @uses EventTarget
  6160. * @constructor
  6161. * @param source {String} the source object (image or canvas)
  6162. */
  6163. PIXI.BaseTexture = function(source)
  6164. {
  6165. PIXI.EventTarget.call( this );
  6166. /**
  6167. * [read-only] The width of the base texture set when the image has loaded
  6168. *
  6169. * @property width
  6170. * @type Number
  6171. * @readOnly
  6172. */
  6173. this.width = 100;
  6174. /**
  6175. * [read-only] The height of the base texture set when the image has loaded
  6176. *
  6177. * @property height
  6178. * @type Number
  6179. * @readOnly
  6180. */
  6181. this.height = 100;
  6182. /**
  6183. * [read-only] Describes if the base texture has loaded or not
  6184. *
  6185. * @property hasLoaded
  6186. * @type Boolean
  6187. * @readOnly
  6188. */
  6189. this.hasLoaded = false;
  6190. /**
  6191. * The source that is loaded to create the texture
  6192. *
  6193. * @property source
  6194. * @type Image
  6195. */
  6196. this.source = source;
  6197. if(!source)return;
  6198. if(this.source instanceof Image || this.source instanceof HTMLImageElement)
  6199. {
  6200. if(this.source.complete)
  6201. {
  6202. this.hasLoaded = true;
  6203. this.width = this.source.width;
  6204. this.height = this.source.height;
  6205. PIXI.texturesToUpdate.push(this);
  6206. }
  6207. else
  6208. {
  6209. var scope = this;
  6210. this.source.onload = function(){
  6211. scope.hasLoaded = true;
  6212. scope.width = scope.source.width;
  6213. scope.height = scope.source.height;
  6214. // add it to somewhere...
  6215. PIXI.texturesToUpdate.push(scope);
  6216. scope.dispatchEvent( { type: 'loaded', content: scope } );
  6217. }
  6218. // this.image.src = imageUrl;
  6219. }
  6220. }
  6221. else
  6222. {
  6223. this.hasLoaded = true;
  6224. this.width = this.source.width;
  6225. this.height = this.source.height;
  6226. PIXI.texturesToUpdate.push(this);
  6227. }
  6228. this._powerOf2 = false;
  6229. }
  6230. PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture;
  6231. /**
  6232. * Destroys this base texture
  6233. *
  6234. * @method destroy
  6235. */
  6236. PIXI.BaseTexture.prototype.destroy = function()
  6237. {
  6238. if(this.source instanceof Image)
  6239. {
  6240. this.source.src = null;
  6241. }
  6242. this.source = null;
  6243. PIXI.texturesToDestroy.push(this);
  6244. }
  6245. /**
  6246. * Helper function that returns a base texture based on an image url
  6247. * If the image is not in the base texture cache it will be created and loaded
  6248. *
  6249. * @static
  6250. * @method fromImage
  6251. * @param imageUrl {String} The image url of the texture
  6252. * @return BaseTexture
  6253. */
  6254. PIXI.BaseTexture.fromImage = function(imageUrl, crossorigin)
  6255. {
  6256. var baseTexture = PIXI.BaseTextureCache[imageUrl];
  6257. if(!baseTexture)
  6258. {
  6259. // new Image() breaks tex loading in some versions of Chrome.
  6260. // See https://code.google.com/p/chromium/issues/detail?id=238071
  6261. var image = new Image();//document.createElement('img');
  6262. if (crossorigin)
  6263. {
  6264. image.crossOrigin = '';
  6265. }
  6266. image.src = imageUrl;
  6267. baseTexture = new PIXI.BaseTexture(image);
  6268. PIXI.BaseTextureCache[imageUrl] = baseTexture;
  6269. }
  6270. return baseTexture;
  6271. }
  6272. /**
  6273. * @author Mat Groves http://matgroves.com/ @Doormat23
  6274. */
  6275. PIXI.TextureCache = {};
  6276. PIXI.FrameCache = {};
  6277. /**
  6278. * A texture stores the information that represents an image or part of an image. It cannot be added
  6279. * to the display list directly. To do this use PIXI.Sprite. If no frame is provided then the whole image is used
  6280. *
  6281. * @class Texture
  6282. * @uses EventTarget
  6283. * @constructor
  6284. * @param baseTexture {BaseTexture} The base texture source to create the texture from
  6285. * @param frame {Rectangle} The rectangle frame of the texture to show
  6286. */
  6287. PIXI.Texture = function(baseTexture, frame)
  6288. {
  6289. PIXI.EventTarget.call( this );
  6290. if(!frame)
  6291. {
  6292. this.noFrame = true;
  6293. frame = new PIXI.Rectangle(0,0,1,1);
  6294. }
  6295. if(baseTexture instanceof PIXI.Texture)
  6296. baseTexture = baseTexture.baseTexture;
  6297. /**
  6298. * The base texture of this texture
  6299. *
  6300. * @property baseTexture
  6301. * @type BaseTexture
  6302. */
  6303. this.baseTexture = baseTexture;
  6304. /**
  6305. * The frame specifies the region of the base texture that this texture uses
  6306. *
  6307. * @property frame
  6308. * @type Rectangle
  6309. */
  6310. this.frame = frame;
  6311. /**
  6312. * The trim point
  6313. *
  6314. * @property trim
  6315. * @type Point
  6316. */
  6317. this.trim = new PIXI.Point();
  6318. this.scope = this;
  6319. if(baseTexture.hasLoaded)
  6320. {
  6321. if(this.noFrame)frame = new PIXI.Rectangle(0,0, baseTexture.width, baseTexture.height);
  6322. //console.log(frame)
  6323. this.setFrame(frame);
  6324. }
  6325. else
  6326. {
  6327. var scope = this;
  6328. baseTexture.addEventListener( 'loaded', function(){ scope.onBaseTextureLoaded()} );
  6329. }
  6330. }
  6331. PIXI.Texture.prototype.constructor = PIXI.Texture;
  6332. /**
  6333. * Called when the base texture is loaded
  6334. *
  6335. * @method onBaseTextureLoaded
  6336. * @param event
  6337. * @private
  6338. */
  6339. PIXI.Texture.prototype.onBaseTextureLoaded = function(event)
  6340. {
  6341. var baseTexture = this.baseTexture;
  6342. baseTexture.removeEventListener( 'loaded', this.onLoaded );
  6343. if(this.noFrame)this.frame = new PIXI.Rectangle(0,0, baseTexture.width, baseTexture.height);
  6344. this.noFrame = false;
  6345. this.width = this.frame.width;
  6346. this.height = this.frame.height;
  6347. this.scope.dispatchEvent( { type: 'update', content: this } );
  6348. }
  6349. /**
  6350. * Destroys this texture
  6351. *
  6352. * @method destroy
  6353. * @param destroyBase {Boolean} Whether to destroy the base texture as well
  6354. */
  6355. PIXI.Texture.prototype.destroy = function(destroyBase)
  6356. {
  6357. if(destroyBase)this.baseTexture.destroy();
  6358. }
  6359. /**
  6360. * Specifies the rectangle region of the baseTexture
  6361. *
  6362. * @method setFrame
  6363. * @param frame {Rectangle} The frame of the texture to set it to
  6364. */
  6365. PIXI.Texture.prototype.setFrame = function(frame)
  6366. {
  6367. this.frame = frame;
  6368. this.width = frame.width;
  6369. this.height = frame.height;
  6370. if(frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)
  6371. {
  6372. throw new Error("Texture Error: frame does not fit inside the base Texture dimensions " + this);
  6373. }
  6374. this.updateFrame = true;
  6375. PIXI.Texture.frameUpdates.push(this);
  6376. //this.dispatchEvent( { type: 'update', content: this } );
  6377. }
  6378. /**
  6379. * Helper function that returns a texture based on an image url
  6380. * If the image is not in the texture cache it will be created and loaded
  6381. *
  6382. * @static
  6383. * @method fromImage
  6384. * @param imageUrl {String} The image url of the texture
  6385. * @param crossorigin {Boolean} Whether requests should be treated as crossorigin
  6386. * @return Texture
  6387. */
  6388. PIXI.Texture.fromImage = function(imageUrl, crossorigin)
  6389. {
  6390. var texture = PIXI.TextureCache[imageUrl];
  6391. if(!texture)
  6392. {
  6393. texture = new PIXI.Texture(PIXI.BaseTexture.fromImage(imageUrl, crossorigin));
  6394. PIXI.TextureCache[imageUrl] = texture;
  6395. }
  6396. return texture;
  6397. }
  6398. /**
  6399. * Helper function that returns a texture based on a frame id
  6400. * If the frame id is not in the texture cache an error will be thrown
  6401. *
  6402. * @static
  6403. * @method fromFrame
  6404. * @param frameId {String} The frame id of the texture
  6405. * @return Texture
  6406. */
  6407. PIXI.Texture.fromFrame = function(frameId)
  6408. {
  6409. var texture = PIXI.TextureCache[frameId];
  6410. if(!texture)throw new Error("The frameId '"+ frameId +"' does not exist in the texture cache " + this);
  6411. return texture;
  6412. }
  6413. /**
  6414. * Helper function that returns a texture based on a canvas element
  6415. * If the canvas is not in the texture cache it will be created and loaded
  6416. *
  6417. * @static
  6418. * @method fromCanvas
  6419. * @param canvas {Canvas} The canvas element source of the texture
  6420. * @return Texture
  6421. */
  6422. PIXI.Texture.fromCanvas = function(canvas)
  6423. {
  6424. var baseTexture = new PIXI.BaseTexture(canvas);
  6425. return new PIXI.Texture(baseTexture);
  6426. }
  6427. /**
  6428. * Adds a texture to the textureCache.
  6429. *
  6430. * @static
  6431. * @method addTextureToCache
  6432. * @param texture {Texture}
  6433. * @param id {String} the id that the texture will be stored against.
  6434. */
  6435. PIXI.Texture.addTextureToCache = function(texture, id)
  6436. {
  6437. PIXI.TextureCache[id] = texture;
  6438. }
  6439. /**
  6440. * Remove a texture from the textureCache.
  6441. *
  6442. * @static
  6443. * @method removeTextureFromCache
  6444. * @param id {String} the id of the texture to be removed
  6445. * @return {Texture} the texture that was removed
  6446. */
  6447. PIXI.Texture.removeTextureFromCache = function(id)
  6448. {
  6449. var texture = PIXI.TextureCache[id]
  6450. PIXI.TextureCache[id] = null;
  6451. return texture;
  6452. }
  6453. // this is more for webGL.. it contains updated frames..
  6454. PIXI.Texture.frameUpdates = [];
  6455. /**
  6456. * @author Mat Groves http://matgroves.com/ @Doormat23
  6457. */
  6458. /**
  6459. A RenderTexture is a special texture that allows any pixi displayObject to be rendered to it.
  6460. __Hint__: All DisplayObjects (exmpl. Sprites) that renders on RenderTexture should be preloaded.
  6461. Otherwise black rectangles will be drawn instead.
  6462. RenderTexture takes snapshot of DisplayObject passed to render method. If DisplayObject is passed to render method, position and rotation of it will be ignored. For example:
  6463. var renderTexture = new PIXI.RenderTexture(800, 600);
  6464. var sprite = PIXI.Sprite.fromImage("spinObj_01.png");
  6465. sprite.position.x = 800/2;
  6466. sprite.position.y = 600/2;
  6467. sprite.anchor.x = 0.5;
  6468. sprite.anchor.y = 0.5;
  6469. renderTexture.render(sprite);
  6470. Sprite in this case will be rendered to 0,0 position. To render this sprite at center DisplayObjectContainer should be used:
  6471. var doc = new PIXI.DisplayObjectContainer();
  6472. doc.addChild(sprite);
  6473. renderTexture.render(doc); // Renders to center of renderTexture
  6474. @class RenderTexture
  6475. @extends Texture
  6476. @constructor
  6477. @param width {Number} The width of the render texture
  6478. @param height {Number} The height of the render texture
  6479. */
  6480. PIXI.RenderTexture = function(width, height)
  6481. {
  6482. PIXI.EventTarget.call( this );
  6483. this.width = width || 100;
  6484. this.height = height || 100;
  6485. this.indetityMatrix = PIXI.mat3.create();
  6486. this.frame = new PIXI.Rectangle(0, 0, this.width, this.height);
  6487. if(PIXI.gl)
  6488. {
  6489. this.initWebGL();
  6490. }
  6491. else
  6492. {
  6493. this.initCanvas();
  6494. }
  6495. }
  6496. PIXI.RenderTexture.prototype = Object.create( PIXI.Texture.prototype );
  6497. PIXI.RenderTexture.prototype.constructor = PIXI.RenderTexture;
  6498. /**
  6499. * Initializes the webgl data for this texture
  6500. *
  6501. * @method initWebGL
  6502. * @private
  6503. */
  6504. PIXI.RenderTexture.prototype.initWebGL = function()
  6505. {
  6506. var gl = PIXI.gl;
  6507. this.glFramebuffer = gl.createFramebuffer();
  6508. gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer );
  6509. this.glFramebuffer.width = this.width;
  6510. this.glFramebuffer.height = this.height;
  6511. this.baseTexture = new PIXI.BaseTexture();
  6512. this.baseTexture.width = this.width;
  6513. this.baseTexture.height = this.height;
  6514. this.baseTexture._glTexture = gl.createTexture();
  6515. gl.bindTexture(gl.TEXTURE_2D, this.baseTexture._glTexture);
  6516. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6517. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6518. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  6519. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6520. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6521. this.baseTexture.isRender = true;
  6522. gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer );
  6523. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.baseTexture._glTexture, 0);
  6524. // create a projection matrix..
  6525. this.projection = new PIXI.Point(this.width/2 , -this.height/2);
  6526. // set the correct render function..
  6527. this.render = this.renderWebGL;
  6528. }
  6529. PIXI.RenderTexture.prototype.resize = function(width, height)
  6530. {
  6531. this.width = width;
  6532. this.height = height;
  6533. if(PIXI.gl)
  6534. {
  6535. this.projection.x = this.width/2
  6536. this.projection.y = -this.height/2;
  6537. var gl = PIXI.gl;
  6538. gl.bindTexture(gl.TEXTURE_2D, this.baseTexture._glTexture);
  6539. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6540. }
  6541. else
  6542. {
  6543. this.frame.width = this.width
  6544. this.frame.height = this.height;
  6545. this.renderer.resize(this.width, this.height);
  6546. }
  6547. }
  6548. /**
  6549. * Initializes the canvas data for this texture
  6550. *
  6551. * @method initCanvas
  6552. * @private
  6553. */
  6554. PIXI.RenderTexture.prototype.initCanvas = function()
  6555. {
  6556. this.renderer = new PIXI.CanvasRenderer(this.width, this.height, null, 0);
  6557. this.baseTexture = new PIXI.BaseTexture(this.renderer.view);
  6558. this.frame = new PIXI.Rectangle(0, 0, this.width, this.height);
  6559. this.render = this.renderCanvas;
  6560. }
  6561. /**
  6562. * This function will draw the display object to the texture.
  6563. *
  6564. * @method renderWebGL
  6565. * @param displayObject {DisplayObject} The display object to render this texture on
  6566. * @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn
  6567. * @private
  6568. */
  6569. PIXI.RenderTexture.prototype.renderWebGL = function(displayObject, position, clear)
  6570. {
  6571. var gl = PIXI.gl;
  6572. // enable the alpha color mask..
  6573. gl.colorMask(true, true, true, true);
  6574. gl.viewport(0, 0, this.width, this.height);
  6575. gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer );
  6576. if(clear)
  6577. {
  6578. gl.clearColor(0,0,0, 0);
  6579. gl.clear(gl.COLOR_BUFFER_BIT);
  6580. }
  6581. // THIS WILL MESS WITH HIT TESTING!
  6582. var children = displayObject.children;
  6583. //TODO -? create a new one??? dont think so!
  6584. var originalWorldTransform = displayObject.worldTransform;
  6585. displayObject.worldTransform = PIXI.mat3.create();//sthis.indetityMatrix;
  6586. // modify to flip...
  6587. displayObject.worldTransform[4] = -1;
  6588. displayObject.worldTransform[5] = this.projection.y * -2;
  6589. if(position)
  6590. {
  6591. displayObject.worldTransform[2] = position.x;
  6592. displayObject.worldTransform[5] -= position.y;
  6593. }
  6594. PIXI.visibleCount++;
  6595. displayObject.vcount = PIXI.visibleCount;
  6596. for(var i=0,j=children.length; i<j; i++)
  6597. {
  6598. children[i].updateTransform();
  6599. }
  6600. var renderGroup = displayObject.__renderGroup;
  6601. if(renderGroup)
  6602. {
  6603. if(displayObject == renderGroup.root)
  6604. {
  6605. renderGroup.render(this.projection, this.glFramebuffer);
  6606. }
  6607. else
  6608. {
  6609. renderGroup.renderSpecific(displayObject, this.projection, this.glFramebuffer);
  6610. }
  6611. }
  6612. else
  6613. {
  6614. if(!this.renderGroup)this.renderGroup = new PIXI.WebGLRenderGroup(gl);
  6615. this.renderGroup.setRenderable(displayObject);
  6616. this.renderGroup.render(this.projection, this.glFramebuffer);
  6617. }
  6618. displayObject.worldTransform = originalWorldTransform;
  6619. }
  6620. /**
  6621. * This function will draw the display object to the texture.
  6622. *
  6623. * @method renderCanvas
  6624. * @param displayObject {DisplayObject} The display object to render this texture on
  6625. * @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn
  6626. * @private
  6627. */
  6628. PIXI.RenderTexture.prototype.renderCanvas = function(displayObject, position, clear)
  6629. {
  6630. var children = displayObject.children;
  6631. displayObject.worldTransform = PIXI.mat3.create();
  6632. if(position)
  6633. {
  6634. displayObject.worldTransform[2] = position.x;
  6635. displayObject.worldTransform[5] = position.y;
  6636. }
  6637. for(var i=0,j=children.length; i<j; i++)
  6638. {
  6639. children[i].updateTransform();
  6640. }
  6641. if(clear)this.renderer.context.clearRect(0,0, this.width, this.height);
  6642. this.renderer.renderDisplayObject(displayObject);
  6643. this.renderer.context.setTransform(1,0,0,1,0,0);
  6644. // PIXI.texturesToUpdate.push(this.baseTexture);
  6645. }
  6646. /**
  6647. * https://github.com/mrdoob/eventtarget.js/
  6648. * THankS mr DOob!
  6649. */
  6650. /**
  6651. * Adds event emitter functionality to a class
  6652. *
  6653. * @class EventTarget
  6654. * @example
  6655. * function MyEmitter() {
  6656. * PIXI.EventTarget.call(this); //mixes in event target stuff
  6657. * }
  6658. *
  6659. * var em = new MyEmitter();
  6660. * em.emit({ type: 'eventName', data: 'some data' });
  6661. */
  6662. PIXI.EventTarget = function () {
  6663. var listeners = {};
  6664. this.addEventListener = this.on = function ( type, listener ) {
  6665. if ( listeners[ type ] === undefined ) {
  6666. listeners[ type ] = [];
  6667. }
  6668. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  6669. listeners[ type ].push( listener );
  6670. }
  6671. };
  6672. this.dispatchEvent = this.emit = function ( event ) {
  6673. if ( !listeners[ event.type ] || !listeners[ event.type ].length ) {
  6674. return;
  6675. }
  6676. for(var i = 0, l = listeners[ event.type ].length; i < l; i++) {
  6677. listeners[ event.type ][ i ]( event );
  6678. }
  6679. };
  6680. this.removeEventListener = this.off = function ( type, listener ) {
  6681. var index = listeners[ type ].indexOf( listener );
  6682. if ( index !== - 1 ) {
  6683. listeners[ type ].splice( index, 1 );
  6684. }
  6685. };
  6686. };
  6687. /*
  6688. PolyK library
  6689. url: http://polyk.ivank.net
  6690. Released under MIT licence.
  6691. Copyright (c) 2012 Ivan Kuckir
  6692. Permission is hereby granted, free of charge, to any person
  6693. obtaining a copy of this software and associated documentation
  6694. files (the "Software"), to deal in the Software without
  6695. restriction, including without limitation the rights to use,
  6696. copy, modify, merge, publish, distribute, sublicense, and/or sell
  6697. copies of the Software, and to permit persons to whom the
  6698. Software is furnished to do so, subject to the following
  6699. conditions:
  6700. The above copyright notice and this permission notice shall be
  6701. included in all copies or substantial portions of the Software.
  6702. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  6703. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  6704. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  6705. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  6706. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  6707. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  6708. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  6709. OTHER DEALINGS IN THE SOFTWARE.
  6710. This is an amazing lib!
  6711. slightly modified by mat groves (matgroves.com);
  6712. */
  6713. PIXI.PolyK = {};
  6714. /**
  6715. * Triangulates shapes for webGL graphic fills
  6716. *
  6717. * @method Triangulate
  6718. * @namespace PolyK
  6719. * @constructor
  6720. */
  6721. PIXI.PolyK.Triangulate = function(p)
  6722. {
  6723. var sign = true;
  6724. var n = p.length>>1;
  6725. if(n<3) return [];
  6726. var tgs = [];
  6727. var avl = [];
  6728. for(var i=0; i<n; i++) avl.push(i);
  6729. var i = 0;
  6730. var al = n;
  6731. while(al > 3)
  6732. {
  6733. var i0 = avl[(i+0)%al];
  6734. var i1 = avl[(i+1)%al];
  6735. var i2 = avl[(i+2)%al];
  6736. var ax = p[2*i0], ay = p[2*i0+1];
  6737. var bx = p[2*i1], by = p[2*i1+1];
  6738. var cx = p[2*i2], cy = p[2*i2+1];
  6739. var earFound = false;
  6740. if(PIXI.PolyK._convex(ax, ay, bx, by, cx, cy, sign))
  6741. {
  6742. earFound = true;
  6743. for(var j=0; j<al; j++)
  6744. {
  6745. var vi = avl[j];
  6746. if(vi==i0 || vi==i1 || vi==i2) continue;
  6747. if(PIXI.PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {earFound = false; break;}
  6748. }
  6749. }
  6750. if(earFound)
  6751. {
  6752. tgs.push(i0, i1, i2);
  6753. avl.splice((i+1)%al, 1);
  6754. al--;
  6755. i = 0;
  6756. }
  6757. else if(i++ > 3*al)
  6758. {
  6759. // need to flip flip reverse it!
  6760. // reset!
  6761. if(sign)
  6762. {
  6763. var tgs = [];
  6764. avl = [];
  6765. for(var i=0; i<n; i++) avl.push(i);
  6766. i = 0;
  6767. al = n;
  6768. sign = false;
  6769. }
  6770. else
  6771. {
  6772. console.log("PIXI Warning: shape too complex to fill")
  6773. return [];
  6774. }
  6775. }
  6776. }
  6777. tgs.push(avl[0], avl[1], avl[2]);
  6778. return tgs;
  6779. }
  6780. /**
  6781. * Checks if a point is within a triangle
  6782. *
  6783. * @class _PointInTriangle
  6784. * @namespace PolyK
  6785. * @private
  6786. */
  6787. PIXI.PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy)
  6788. {
  6789. var v0x = cx-ax;
  6790. var v0y = cy-ay;
  6791. var v1x = bx-ax;
  6792. var v1y = by-ay;
  6793. var v2x = px-ax;
  6794. var v2y = py-ay;
  6795. var dot00 = v0x*v0x+v0y*v0y;
  6796. var dot01 = v0x*v1x+v0y*v1y;
  6797. var dot02 = v0x*v2x+v0y*v2y;
  6798. var dot11 = v1x*v1x+v1y*v1y;
  6799. var dot12 = v1x*v2x+v1y*v2y;
  6800. var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
  6801. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  6802. var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
  6803. // Check if point is in triangle
  6804. return (u >= 0) && (v >= 0) && (u + v < 1);
  6805. }
  6806. /**
  6807. * Checks if a shape is convex
  6808. *
  6809. * @class _convex
  6810. * @namespace PolyK
  6811. * @private
  6812. */
  6813. PIXI.PolyK._convex = function(ax, ay, bx, by, cx, cy, sign)
  6814. {
  6815. return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) == sign;
  6816. }
  6817. /**
  6818. * @author Richard Davey <rich@photonstorm.com>
  6819. * @copyright 2013 Photon Storm Ltd.
  6820. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  6821. */
  6822. /**
  6823. * A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view.
  6824. * The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y
  6825. *
  6826. * @class Phaser.Camera
  6827. * @constructor
  6828. * @param {Phaser.Game} game - Game reference to the currently running game.
  6829. * @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera
  6830. * @param {number} x - Position of the camera on the X axis
  6831. * @param {number} y - Position of the camera on the Y axis
  6832. * @param {number} width - The width of the view rectangle
  6833. * @param {number} height - The height of the view rectangle
  6834. */
  6835. Phaser.Camera = function (game, id, x, y, width, height) {
  6836. /**
  6837. * @property {Phaser.Game} game - A reference to the currently running Game.
  6838. */
  6839. this.game = game;
  6840. /**
  6841. * @property {Phaser.World} world - A reference to the game world.
  6842. */
  6843. this.world = game.world;
  6844. /**
  6845. * @property {number} id - Reserved for future multiple camera set-ups.
  6846. * @default
  6847. */
  6848. this.id = 0;
  6849. /**
  6850. * Camera view.
  6851. * The view into the world we wish to render (by default the game dimensions).
  6852. * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render.
  6853. * Objects outside of this view are not rendered (unless set to ignore the Camera, i.e. UI?).
  6854. * @property {Phaser.Rectangle} view
  6855. */
  6856. this.view = new Phaser.Rectangle(x, y, width, height);
  6857. /**
  6858. * @property {Phaser.Rectangle} screenView - Used by Sprites to work out Camera culling.
  6859. */
  6860. this.screenView = new Phaser.Rectangle(x, y, width, height);
  6861. /**
  6862. * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World.
  6863. * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound
  6864. * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the center of the world.
  6865. * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere.
  6866. */
  6867. this.bounds = new Phaser.Rectangle(x, y, width, height);
  6868. /**
  6869. * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause camera moving.
  6870. */
  6871. this.deadzone = null;
  6872. /**
  6873. * @property {boolean} visible - Whether this camera is visible or not.
  6874. * @default
  6875. */
  6876. this.visible = true;
  6877. /**
  6878. * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not.
  6879. */
  6880. this.atLimit = { x: false, y: false };
  6881. /**
  6882. * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null.
  6883. * @default
  6884. */
  6885. this.target = null;
  6886. /**
  6887. * @property {number} edge - Edge property.
  6888. * @private
  6889. * @default
  6890. */
  6891. this._edge = 0;
  6892. this.displayObject = null;
  6893. };
  6894. /**
  6895. * @constant
  6896. * @type {number}
  6897. */
  6898. Phaser.Camera.FOLLOW_LOCKON = 0;
  6899. /**
  6900. * @constant
  6901. * @type {number}
  6902. */
  6903. Phaser.Camera.FOLLOW_PLATFORMER = 1;
  6904. /**
  6905. * @constant
  6906. * @type {number}
  6907. */
  6908. Phaser.Camera.FOLLOW_TOPDOWN = 2;
  6909. /**
  6910. * @constant
  6911. * @type {number}
  6912. */
  6913. Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3;
  6914. Phaser.Camera.prototype = {
  6915. /**
  6916. * Tells this camera which sprite to follow.
  6917. * @method Phaser.Camera#follow
  6918. * @param {Phaser.Sprite} target - The object you want the camera to track. Set to null to not follow anything.
  6919. * @param {number} [style] Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow().
  6920. */
  6921. follow: function (target, style) {
  6922. if (typeof style === "undefined") { style = Phaser.Camera.FOLLOW_LOCKON; }
  6923. this.target = target;
  6924. var helper;
  6925. switch (style) {
  6926. case Phaser.Camera.FOLLOW_PLATFORMER:
  6927. var w = this.width / 8;
  6928. var h = this.height / 3;
  6929. this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h);
  6930. break;
  6931. case Phaser.Camera.FOLLOW_TOPDOWN:
  6932. helper = Math.max(this.width, this.height) / 4;
  6933. this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
  6934. break;
  6935. case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT:
  6936. helper = Math.max(this.width, this.height) / 8;
  6937. this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
  6938. break;
  6939. case Phaser.Camera.FOLLOW_LOCKON:
  6940. this.deadzone = null;
  6941. break;
  6942. default:
  6943. this.deadzone = null;
  6944. break;
  6945. }
  6946. },
  6947. /**
  6948. * Move the camera focus on a display object instantly.
  6949. * @method Phaser.Camera#focusOn
  6950. * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties.
  6951. */
  6952. focusOn: function (displayObject) {
  6953. this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight));
  6954. },
  6955. /**
  6956. * Move the camera focus on a location instantly.
  6957. * @method Phaser.Camera#focusOnXY
  6958. * @param {number} x - X position.
  6959. * @param {number} y - Y position.
  6960. */
  6961. focusOnXY: function (x, y) {
  6962. this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight));
  6963. },
  6964. /**
  6965. * Update focusing and scrolling.
  6966. * @method Phaser.Camera#update
  6967. */
  6968. update: function () {
  6969. if (this.target)
  6970. {
  6971. this.updateTarget();
  6972. }
  6973. if (this.bounds)
  6974. {
  6975. this.checkBounds();
  6976. }
  6977. this.displayObject.position.x = -this.view.x;
  6978. this.displayObject.position.y = -this.view.y;
  6979. },
  6980. updateTarget: function () {
  6981. if (this.deadzone)
  6982. {
  6983. this._edge = this.target.x - this.deadzone.x;
  6984. if (this.view.x > this._edge)
  6985. {
  6986. this.view.x = this._edge;
  6987. }
  6988. this._edge = this.target.x + this.target.width - this.deadzone.x - this.deadzone.width;
  6989. if (this.view.x < this._edge)
  6990. {
  6991. this.view.x = this._edge;
  6992. }
  6993. this._edge = this.target.y - this.deadzone.y;
  6994. if (this.view.y > this._edge)
  6995. {
  6996. this.view.y = this._edge;
  6997. }
  6998. this._edge = this.target.y + this.target.height - this.deadzone.y - this.deadzone.height;
  6999. if (this.view.y < this._edge)
  7000. {
  7001. this.view.y = this._edge;
  7002. }
  7003. }
  7004. else
  7005. {
  7006. this.focusOnXY(this.target.x, this.target.y);
  7007. }
  7008. },
  7009. setBoundsToWorld: function () {
  7010. this.bounds.setTo(this.game.world.x, this.game.world.y, this.game.world.width, this.game.world.height);
  7011. },
  7012. /**
  7013. * Method called to ensure the camera doesn't venture outside of the game world.
  7014. * @method Phaser.Camera#checkWorldBounds
  7015. */
  7016. checkBounds: function () {
  7017. this.atLimit.x = false;
  7018. this.atLimit.y = false;
  7019. // Make sure we didn't go outside the cameras bounds
  7020. if (this.view.x < this.bounds.x)
  7021. {
  7022. this.atLimit.x = true;
  7023. this.view.x = this.bounds.x;
  7024. }
  7025. if (this.view.x > this.bounds.right - this.width)
  7026. {
  7027. this.atLimit.x = true;
  7028. this.view.x = (this.bounds.right - this.width) + 1;
  7029. }
  7030. if (this.view.y < this.bounds.top)
  7031. {
  7032. this.atLimit.y = true;
  7033. this.view.y = this.bounds.top;
  7034. }
  7035. if (this.view.y > this.bounds.bottom - this.height)
  7036. {
  7037. this.atLimit.y = true;
  7038. this.view.y = (this.bounds.bottom - this.height) + 1;
  7039. }
  7040. this.view.floor();
  7041. },
  7042. /**
  7043. * A helper function to set both the X and Y properties of the camera at once
  7044. * without having to use game.camera.x and game.camera.y.
  7045. *
  7046. * @method Phaser.Camera#setPosition
  7047. * @param {number} x - X position.
  7048. * @param {number} y - Y position.
  7049. */
  7050. setPosition: function (x, y) {
  7051. this.view.x = x;
  7052. this.view.y = y;
  7053. if (this.bounds)
  7054. {
  7055. this.checkBounds();
  7056. }
  7057. },
  7058. /**
  7059. * Sets the size of the view rectangle given the width and height in parameters.
  7060. *
  7061. * @method Phaser.Camera#setSize
  7062. * @param {number} width - The desired width.
  7063. * @param {number} height - The desired height.
  7064. */
  7065. setSize: function (width, height) {
  7066. this.view.width = width;
  7067. this.view.height = height;
  7068. }
  7069. };
  7070. /**
  7071. * The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds.
  7072. * @name Phaser.Camera#x
  7073. * @property {number} x - Gets or sets the cameras x position.
  7074. */
  7075. Object.defineProperty(Phaser.Camera.prototype, "x", {
  7076. get: function () {
  7077. return this.view.x;
  7078. },
  7079. set: function (value) {
  7080. this.view.x = value;
  7081. if (this.bounds)
  7082. {
  7083. this.checkBounds();
  7084. }
  7085. }
  7086. });
  7087. /**
  7088. * The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds.
  7089. * @name Phaser.Camera#y
  7090. * @property {number} y - Gets or sets the cameras y position.
  7091. */
  7092. Object.defineProperty(Phaser.Camera.prototype, "y", {
  7093. get: function () {
  7094. return this.view.y;
  7095. },
  7096. set: function (value) {
  7097. this.view.y = value;
  7098. if (this.bounds)
  7099. {
  7100. this.checkBounds();
  7101. }
  7102. }
  7103. });
  7104. /**
  7105. * The Cameras width. By default this is the same as the Game size and should not be adjusted for now.
  7106. * @name Phaser.Camera#width
  7107. * @property {number} width - Gets or sets the cameras width.
  7108. */
  7109. Object.defineProperty(Phaser.Camera.prototype, "width", {
  7110. get: function () {
  7111. return this.view.width;
  7112. },
  7113. set: function (value) {
  7114. this.view.width = value;
  7115. }
  7116. });
  7117. /**
  7118. * The Cameras height. By default this is the same as the Game size and should not be adjusted for now.
  7119. * @name Phaser.Camera#height
  7120. * @property {number} height - Gets or sets the cameras height.
  7121. */
  7122. Object.defineProperty(Phaser.Camera.prototype, "height", {
  7123. get: function () {
  7124. return this.view.height;
  7125. },
  7126. set: function (value) {
  7127. this.view.height = value;
  7128. }
  7129. });
  7130. /**
  7131. * @author Richard Davey <rich@photonstorm.com>
  7132. * @copyright 2013 Photon Storm Ltd.
  7133. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  7134. */
  7135. /**
  7136. * This is a base State class which can be extended if you are creating your own game.
  7137. * It provides quick access to common functions such as the camera, cache, input, match, sound and more.
  7138. *
  7139. * @class Phaser.State
  7140. * @constructor
  7141. */
  7142. Phaser.State = function () {
  7143. /**
  7144. * @property {Phaser.Game} game - A reference to the currently running Game.
  7145. */
  7146. this.game = null;
  7147. /**
  7148. * @property {Phaser.GameObjectFactory} add - Reference to the GameObjectFactory.
  7149. * @default
  7150. */
  7151. this.add = null;
  7152. /**
  7153. * @property {Phaser.Camera} camera - A handy reference to world.camera.
  7154. * @default
  7155. */
  7156. this.camera = null;
  7157. /**
  7158. * @property {Phaser.Cache} cache - Reference to the assets cache.
  7159. * @default
  7160. */
  7161. this.cache = null;
  7162. /**
  7163. * @property {Phaser.Input} input - Reference to the input manager
  7164. * @default
  7165. */
  7166. this.input = null;
  7167. /**
  7168. * @property {Phaser.Loader} load - Reference to the assets loader.
  7169. * @default
  7170. */
  7171. this.load = null;
  7172. /**
  7173. * @property {Phaser.Math} math - Reference to the math helper.
  7174. * @default
  7175. */
  7176. this.math = null;
  7177. /**
  7178. * @property {Phaser.SoundManager} sound - Reference to the sound manager.
  7179. * @default
  7180. */
  7181. this.sound = null;
  7182. /**
  7183. * @property {Phaser.Stage} stage - Reference to the stage.
  7184. * @default
  7185. */
  7186. this.stage = null;
  7187. /**
  7188. * @property {Phaser.TimeManager} time - Reference to game clock.
  7189. * @default
  7190. */
  7191. this.time = null;
  7192. /**
  7193. * @property {Phaser.TweenManager} tweens - Reference to the tween manager.
  7194. * @default
  7195. */
  7196. this.tweens = null;
  7197. /**
  7198. * @property {Phaser.World} world - Reference to the world.
  7199. * @default
  7200. */
  7201. this.world = null;
  7202. /**
  7203. * @property {Phaser.Particles} particles - The Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it.
  7204. * @default
  7205. */
  7206. this.particles = null;
  7207. /**
  7208. * @property {Phaser.Physics.PhysicsManager} physics - Reference to the physics manager.
  7209. * @default
  7210. */
  7211. this.physics = null;
  7212. };
  7213. Phaser.State.prototype = {
  7214. /**
  7215. * Override this method to add some load operations.
  7216. * If you need to use the loader, you may need to use them here.
  7217. *
  7218. * @method Phaser.State#preload
  7219. */
  7220. preload: function () {
  7221. },
  7222. /**
  7223. * Put update logic here.
  7224. *
  7225. * @method Phaser.State#loadUpdate
  7226. */
  7227. loadUpdate: function () {
  7228. },
  7229. /**
  7230. * Put render operations here.
  7231. *
  7232. * @method Phaser.State#loadRender
  7233. */
  7234. loadRender: function () {
  7235. },
  7236. /**
  7237. * This method is called after the game engine successfully switches states.
  7238. * Feel free to add any setup code here (do not load anything here, override preload() instead).
  7239. *
  7240. * @method Phaser.State#create
  7241. */
  7242. create: function () {
  7243. },
  7244. /**
  7245. * Put update logic here.
  7246. *
  7247. * @method Phaser.State#update
  7248. */
  7249. update: function () {
  7250. },
  7251. /**
  7252. * Put render operations here.
  7253. *
  7254. * @method Phaser.State#render
  7255. */
  7256. render: function () {
  7257. },
  7258. /**
  7259. * This method will be called when game paused.
  7260. *
  7261. * @method Phaser.State#paused
  7262. */
  7263. paused: function () {
  7264. },
  7265. /**
  7266. * This method will be called when the state is destroyed.
  7267. * @method Phaser.State#destroy
  7268. */
  7269. destroy: function () {
  7270. }
  7271. };
  7272. /* jshint newcap: false */
  7273. /**
  7274. * @author Richard Davey <rich@photonstorm.com>
  7275. * @copyright 2013 Photon Storm Ltd.
  7276. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  7277. */
  7278. /**
  7279. * The State Manager is responsible for loading, setting up and switching game states.
  7280. *
  7281. * @class Phaser.StateManager
  7282. * @constructor
  7283. * @param {Phaser.Game} game - A reference to the currently running game.
  7284. * @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with.
  7285. */
  7286. Phaser.StateManager = function (game, pendingState) {
  7287. /**
  7288. * @property {Phaser.Game} game - A reference to the currently running game.
  7289. */
  7290. this.game = game;
  7291. /**
  7292. * @property {Object} states - The object containing Phaser.States.
  7293. */
  7294. this.states = {};
  7295. /**
  7296. * @property {Phaser.State} _pendingState - The state to be switched to in the next frame.
  7297. * @private
  7298. */
  7299. this._pendingState = null;
  7300. if (pendingState !== null)
  7301. {
  7302. this._pendingState = pendingState;
  7303. }
  7304. /**
  7305. * @property {boolean} _created - Flag that sets if the State has been created or not.
  7306. * @private
  7307. */
  7308. this._created = false;
  7309. /**
  7310. * @property {string} current - The current active State object (defaults to null).
  7311. */
  7312. this.current = '';
  7313. /**
  7314. * @property {function} onInitCallback - This will be called when the state is started (i.e. set as the current active state).
  7315. */
  7316. this.onInitCallback = null;
  7317. /**
  7318. * @property {function} onPreloadCallback - This will be called when init states (loading assets...).
  7319. */
  7320. this.onPreloadCallback = null;
  7321. /**
  7322. * @property {function} onCreateCallback - This will be called when create states (setup states...).
  7323. */
  7324. this.onCreateCallback = null;
  7325. /**
  7326. * @property {function} onUpdateCallback - This will be called when State is updated, this doesn't happen during load (@see onLoadUpdateCallback).
  7327. */
  7328. this.onUpdateCallback = null;
  7329. /**
  7330. * @property {function} onRenderCallback - This will be called when the State is rendered, this doesn't happen during load (see onLoadRenderCallback).
  7331. */
  7332. this.onRenderCallback = null;
  7333. /**
  7334. * @property {function} onPreRenderCallback - This will be called before the State is rendered and before the stage is cleared.
  7335. */
  7336. this.onPreRenderCallback = null;
  7337. /**
  7338. * @property {function} onLoadUpdateCallback - This will be called when the State is updated but only during the load process.
  7339. */
  7340. this.onLoadUpdateCallback = null;
  7341. /**
  7342. * @property {function} onLoadRenderCallback - This will be called when the State is rendered but only during the load process.
  7343. */
  7344. this.onLoadRenderCallback = null;
  7345. /**
  7346. * @property {function} onPausedCallback - This will be called when the state is paused.
  7347. */
  7348. this.onPausedCallback = null;
  7349. /**
  7350. * @property {function} onShutDownCallback - This will be called when the state is shut down (i.e. swapped to another state).
  7351. */
  7352. this.onShutDownCallback = null;
  7353. };
  7354. Phaser.StateManager.prototype = {
  7355. /**
  7356. * The Boot handler is called by Phaser.Game when it first starts up.
  7357. * @method Phaser.StateManager#boot
  7358. * @private
  7359. */
  7360. boot: function () {
  7361. this.game.onPause.add(this.pause, this);
  7362. this.game.onResume.add(this.resume, this);
  7363. if (this._pendingState !== null)
  7364. {
  7365. if (typeof this._pendingState === 'string')
  7366. {
  7367. // State was already added, so just start it
  7368. this.start(this._pendingState, false, false);
  7369. }
  7370. else
  7371. {
  7372. this.add('default', this._pendingState, true);
  7373. }
  7374. }
  7375. },
  7376. /**
  7377. * Add a new State.
  7378. * @method Phaser.StateManager#add
  7379. * @param key {string} - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
  7380. * @param state {State} - The state you want to switch to.
  7381. * @param autoStart {boolean} - Start the state immediately after creating it? (default true)
  7382. */
  7383. add: function (key, state, autoStart) {
  7384. if (typeof autoStart === "undefined") { autoStart = false; }
  7385. var newState;
  7386. if (state instanceof Phaser.State)
  7387. {
  7388. newState = state;
  7389. }
  7390. else if (typeof state === 'object')
  7391. {
  7392. newState = state;
  7393. newState.game = this.game;
  7394. }
  7395. else if (typeof state === 'function')
  7396. {
  7397. newState = new state(this.game);
  7398. }
  7399. this.states[key] = newState;
  7400. if (autoStart)
  7401. {
  7402. if (this.game.isBooted)
  7403. {
  7404. this.start(key);
  7405. }
  7406. else
  7407. {
  7408. this._pendingState = key;
  7409. }
  7410. }
  7411. return newState;
  7412. },
  7413. /**
  7414. * Delete the given state.
  7415. * @method Phaser.StateManager#remove
  7416. * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
  7417. */
  7418. remove: function (key) {
  7419. if (this.current == key)
  7420. {
  7421. this.callbackContext = null;
  7422. this.onInitCallback = null;
  7423. this.onShutDownCallback = null;
  7424. this.onPreloadCallback = null;
  7425. this.onLoadRenderCallback = null;
  7426. this.onLoadUpdateCallback = null;
  7427. this.onCreateCallback = null;
  7428. this.onUpdateCallback = null;
  7429. this.onRenderCallback = null;
  7430. this.onPausedCallback = null;
  7431. this.onDestroyCallback = null;
  7432. }
  7433. delete this.states[key];
  7434. },
  7435. /**
  7436. * Start the given state
  7437. * @method Phaser.StateManager#start
  7438. * @param {string} key - The key of the state you want to start.
  7439. * @param {boolean} [clearWorld] - clear everything in the world? (Default to true)
  7440. * @param {boolean} [clearCache] - clear asset cache? (Default to false and ONLY available when clearWorld=true)
  7441. */
  7442. start: function (key, clearWorld, clearCache) {
  7443. if (typeof clearWorld === "undefined") { clearWorld = true; }
  7444. if (typeof clearCache === "undefined") { clearCache = false; }
  7445. if (this.game.isBooted === false)
  7446. {
  7447. this._pendingState = key;
  7448. return;
  7449. }
  7450. if (this.checkState(key) === false)
  7451. {
  7452. return;
  7453. }
  7454. else
  7455. {
  7456. // Already got a state running?
  7457. if (this.current)
  7458. {
  7459. this.onShutDownCallback.call(this.callbackContext, this.game);
  7460. }
  7461. if (clearWorld)
  7462. {
  7463. this.game.tweens.removeAll();
  7464. this.game.world.destroy();
  7465. if (clearCache === true)
  7466. {
  7467. this.game.cache.destroy();
  7468. }
  7469. }
  7470. this.setCurrentState(key);
  7471. }
  7472. if (this.onPreloadCallback)
  7473. {
  7474. this.game.load.reset();
  7475. this.onPreloadCallback.call(this.callbackContext, this.game);
  7476. // Is the loader empty?
  7477. if (this.game.load.totalQueuedFiles() === 0)
  7478. {
  7479. this.game.loadComplete();
  7480. }
  7481. else
  7482. {
  7483. // Start the loader going as we have something in the queue
  7484. this.game.load.start();
  7485. }
  7486. }
  7487. else
  7488. {
  7489. // No init? Then there was nothing to load either
  7490. this.game.loadComplete();
  7491. }
  7492. },
  7493. /**
  7494. * Used by onInit and onShutdown when those functions don't exist on the state
  7495. * @method Phaser.StateManager#dummy
  7496. * @private
  7497. */
  7498. dummy: function () {
  7499. },
  7500. /**
  7501. * Description.
  7502. * @method Phaser.StateManager#checkState
  7503. * @param {string} key - The key of the state you want to check.
  7504. * @return {boolean} Description.
  7505. */
  7506. checkState: function (key) {
  7507. if (this.states[key])
  7508. {
  7509. var valid = false;
  7510. if (this.states[key]['preload']) { valid = true; }
  7511. if (valid === false && this.states[key]['loadRender']) { valid = true; }
  7512. if (valid === false && this.states[key]['loadUpdate']) { valid = true; }
  7513. if (valid === false && this.states[key]['create']) { valid = true; }
  7514. if (valid === false && this.states[key]['update']) { valid = true; }
  7515. if (valid === false && this.states[key]['preRender']) { valid = true; }
  7516. if (valid === false && this.states[key]['render']) { valid = true; }
  7517. if (valid === false && this.states[key]['paused']) { valid = true; }
  7518. if (valid === false)
  7519. {
  7520. console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions.");
  7521. return false;
  7522. }
  7523. return true;
  7524. }
  7525. else
  7526. {
  7527. console.warn("Phaser.StateManager - No state found with the key: " + key);
  7528. return false;
  7529. }
  7530. },
  7531. /**
  7532. * Links game properties to the State given by the key.
  7533. * @method Phaser.StateManager#link
  7534. * @param {string} key - State key.
  7535. * @protected
  7536. */
  7537. link: function (key) {
  7538. this.states[key].game = this.game;
  7539. this.states[key].add = this.game.add;
  7540. this.states[key].camera = this.game.camera;
  7541. this.states[key].cache = this.game.cache;
  7542. this.states[key].input = this.game.input;
  7543. this.states[key].load = this.game.load;
  7544. this.states[key].math = this.game.math;
  7545. this.states[key].sound = this.game.sound;
  7546. this.states[key].stage = this.game.stage;
  7547. this.states[key].time = this.game.time;
  7548. this.states[key].tweens = this.game.tweens;
  7549. this.states[key].world = this.game.world;
  7550. this.states[key].particles = this.game.particles;
  7551. this.states[key].physics = this.game.physics;
  7552. this.states[key].rnd = this.game.rnd;
  7553. },
  7554. /**
  7555. * Sets the current State. Should not be called directly (use StateManager.start)
  7556. * @method Phaser.StateManager#setCurrentState
  7557. * @param {string} key - State key.
  7558. * @protected
  7559. */
  7560. setCurrentState: function (key) {
  7561. this.callbackContext = this.states[key];
  7562. this.link(key);
  7563. // Used when the state is set as being the current active state
  7564. this.onInitCallback = this.states[key]['init'] || this.dummy;
  7565. this.onPreloadCallback = this.states[key]['preload'] || null;
  7566. this.onLoadRenderCallback = this.states[key]['loadRender'] || null;
  7567. this.onLoadUpdateCallback = this.states[key]['loadUpdate'] || null;
  7568. this.onCreateCallback = this.states[key]['create'] || null;
  7569. this.onUpdateCallback = this.states[key]['update'] || null;
  7570. this.onPreRenderCallback = this.states[key]['preRender'] || null;
  7571. this.onRenderCallback = this.states[key]['render'] || null;
  7572. this.onPausedCallback = this.states[key]['paused'] || null;
  7573. // Used when the state is no longer the current active state
  7574. this.onShutDownCallback = this.states[key]['shutdown'] || this.dummy;
  7575. this.current = key;
  7576. this._created = false;
  7577. this.onInitCallback.call(this.callbackContext, this.game);
  7578. },
  7579. /**
  7580. * @method Phaser.StateManager#loadComplete
  7581. * @protected
  7582. */
  7583. loadComplete: function () {
  7584. if (this._created === false && this.onCreateCallback)
  7585. {
  7586. this._created = true;
  7587. this.onCreateCallback.call(this.callbackContext, this.game);
  7588. }
  7589. else
  7590. {
  7591. this._created = true;
  7592. }
  7593. },
  7594. /**
  7595. * @method Phaser.StateManager#pause
  7596. * @protected
  7597. */
  7598. pause: function () {
  7599. if (this._created && this.onPausedCallback)
  7600. {
  7601. this.onPausedCallback.call(this.callbackContext, this.game, true);
  7602. }
  7603. },
  7604. /**
  7605. * @method Phaser.StateManager#resume
  7606. * @protected
  7607. */
  7608. resume: function () {
  7609. if (this._created && this.onre)
  7610. {
  7611. this.onPausedCallback.call(this.callbackContext, this.game, false);
  7612. }
  7613. },
  7614. /**
  7615. * @method Phaser.StateManager#update
  7616. * @protected
  7617. */
  7618. update: function () {
  7619. if (this._created && this.onUpdateCallback)
  7620. {
  7621. this.onUpdateCallback.call(this.callbackContext, this.game);
  7622. }
  7623. else
  7624. {
  7625. if (this.onLoadUpdateCallback)
  7626. {
  7627. this.onLoadUpdateCallback.call(this.callbackContext, this.game);
  7628. }
  7629. }
  7630. },
  7631. /**
  7632. * @method Phaser.StateManager#preRender
  7633. * @protected
  7634. */
  7635. preRender: function () {
  7636. if (this.onPreRenderCallback)
  7637. {
  7638. this.onPreRenderCallback.call(this.callbackContext, this.game);
  7639. }
  7640. },
  7641. /**
  7642. * @method Phaser.StateManager#render
  7643. * @protected
  7644. */
  7645. render: function () {
  7646. if (this._created && this.onRenderCallback)
  7647. {
  7648. if (this.game.renderType === Phaser.CANVAS)
  7649. {
  7650. this.game.context.save();
  7651. this.game.context.setTransform(1, 0, 0, 1, 0, 0);
  7652. }
  7653. this.onRenderCallback.call(this.callbackContext, this.game);
  7654. if (this.game.renderType === Phaser.CANVAS)
  7655. {
  7656. this.game.context.restore();
  7657. }
  7658. }
  7659. else
  7660. {
  7661. if (this.onLoadRenderCallback)
  7662. {
  7663. this.onLoadRenderCallback.call(this.callbackContext, this.game);
  7664. }
  7665. }
  7666. },
  7667. /**
  7668. * Nuke the entire game from orbit
  7669. * @method Phaser.StateManager#destroy
  7670. */
  7671. destroy: function () {
  7672. this.callbackContext = null;
  7673. this.onInitCallback = null;
  7674. this.onShutDownCallback = null;
  7675. this.onPreloadCallback = null;
  7676. this.onLoadRenderCallback = null;
  7677. this.onLoadUpdateCallback = null;
  7678. this.onCreateCallback = null;
  7679. this.onUpdateCallback = null;
  7680. this.onRenderCallback = null;
  7681. this.onPausedCallback = null;
  7682. this.onDestroyCallback = null;
  7683. this.game = null;
  7684. this.states = {};
  7685. this._pendingState = null;
  7686. }
  7687. };
  7688. /**
  7689. * @author Richard Davey <rich@photonstorm.com>
  7690. * @copyright 2013 Photon Storm Ltd.
  7691. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  7692. */
  7693. /**
  7694. * A basic linked list data structure.
  7695. *
  7696. * @class Phaser.LinkedList
  7697. * @constructor
  7698. */
  7699. Phaser.LinkedList = function () {
  7700. /**
  7701. * @property {object} next - Next element in the list.
  7702. * @default
  7703. */
  7704. this.next = null;
  7705. /**
  7706. * @property {object} prev - Previous element in the list.
  7707. * @default
  7708. */
  7709. this.prev = null;
  7710. /**
  7711. * @property {object} first - First element in the list.
  7712. * @default
  7713. */
  7714. this.first = null;
  7715. /**
  7716. * @property {object} last - Last element in the list.
  7717. * @default
  7718. */
  7719. this.last = null;
  7720. /**
  7721. * @property {object} game - Number of elements in the list.
  7722. * @default
  7723. */
  7724. this.total = 0;
  7725. };
  7726. Phaser.LinkedList.prototype = {
  7727. /**
  7728. * Adds a new element to this linked list.
  7729. *
  7730. * @method Phaser.LinkedList#add
  7731. * @param {object} child - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
  7732. * @return {object} The child that was added.
  7733. */
  7734. add: function (child) {
  7735. // If the list is empty
  7736. if (this.total === 0 && this.first == null && this.last == null)
  7737. {
  7738. this.first = child;
  7739. this.last = child;
  7740. this.next = child;
  7741. child.prev = this;
  7742. this.total++;
  7743. return child;
  7744. }
  7745. // Get gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list)
  7746. this.last.next = child;
  7747. child.prev = this.last;
  7748. this.last = child;
  7749. this.total++;
  7750. return child;
  7751. },
  7752. /**
  7753. * Removes the given element from this linked list if it exists.
  7754. *
  7755. * @method Phaser.LinkedList#remove
  7756. * @param {object} child - The child to be removed from the list.
  7757. */
  7758. remove: function (child) {
  7759. if (child == this.first)
  7760. {
  7761. // It was 'first', make 'first' point to first.next
  7762. this.first = this.first.next;
  7763. }
  7764. else if (child == this.last)
  7765. {
  7766. // It was 'last', make 'last' point to last.prev
  7767. this.last = this.last.prev;
  7768. }
  7769. if (child.prev)
  7770. {
  7771. // make child.prev.next point to childs.next instead of child
  7772. child.prev.next = child.next;
  7773. }
  7774. if (child.next)
  7775. {
  7776. // make child.next.prev point to child.prev instead of child
  7777. child.next.prev = child.prev;
  7778. }
  7779. child.next = child.prev = null;
  7780. if (this.first == null )
  7781. {
  7782. this.last = null;
  7783. }
  7784. this.total--;
  7785. },
  7786. /**
  7787. * Calls a function on all members of this list, using the member as the context for the callback.
  7788. * The function must exist on the member.
  7789. *
  7790. * @method Phaser.LinkedList#callAll
  7791. * @param {function} callback - The function to call.
  7792. */
  7793. callAll: function (callback) {
  7794. if (!this.first || !this.last)
  7795. {
  7796. return;
  7797. }
  7798. var entity = this.first;
  7799. do
  7800. {
  7801. if (entity && entity[callback])
  7802. {
  7803. entity[callback].call(entity);
  7804. }
  7805. entity = entity.next;
  7806. }
  7807. while(entity != this.last.next)
  7808. }
  7809. };
  7810. /**
  7811. * @author Richard Davey <rich@photonstorm.com>
  7812. * @copyright 2013 Photon Storm Ltd.
  7813. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  7814. */
  7815. /**
  7816. * @class Phaser.Signal
  7817. * @classdesc A Signal is used for object communication via a custom broadcaster instead of Events.
  7818. * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
  7819. * @constructor
  7820. */
  7821. Phaser.Signal = function () {
  7822. /**
  7823. * @property {Array.<Phaser.SignalBinding>} _bindings - Internal variable.
  7824. * @private
  7825. */
  7826. this._bindings = [];
  7827. /**
  7828. * @property {any} _prevParams - Internal variable.
  7829. * @private
  7830. */
  7831. this._prevParams = null;
  7832. // enforce dispatch to aways work on same context (#47)
  7833. var self = this;
  7834. /**
  7835. * @property {function} dispatch - The dispatch function is what sends the Signal out.
  7836. */
  7837. this.dispatch = function(){
  7838. Phaser.Signal.prototype.dispatch.apply(self, arguments);
  7839. };
  7840. };
  7841. Phaser.Signal.prototype = {
  7842. /**
  7843. * If Signal should keep record of previously dispatched parameters and
  7844. * automatically execute listener during `add()`/`addOnce()` if Signal was
  7845. * already dispatched before.
  7846. * @property {boolean} memorize
  7847. */
  7848. memorize: false,
  7849. /**
  7850. * @property {boolean} _shouldPropagate
  7851. * @private
  7852. */
  7853. _shouldPropagate: true,
  7854. /**
  7855. * If Signal is active and should broadcast events.
  7856. * <p><strong>IMPORTANT:</strong> Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.</p>
  7857. * @property {boolean} active
  7858. * @default
  7859. */
  7860. active: true,
  7861. /**
  7862. * @method Phaser.Signal#validateListener
  7863. * @param {function} listener - Signal handler function.
  7864. * @param {string} fnName - Function name.
  7865. * @private
  7866. */
  7867. validateListener: function (listener, fnName) {
  7868. if (typeof listener !== 'function') {
  7869. throw new Error( 'listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName) );
  7870. }
  7871. },
  7872. /**
  7873. * @method Phaser.Signal#_registerListener
  7874. * @param {function} listener - Signal handler function.
  7875. * @param {boolean} isOnce - Description.
  7876. * @param {object} [listenerContext] - Description.
  7877. * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0).
  7878. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  7879. * @private
  7880. */
  7881. _registerListener: function (listener, isOnce, listenerContext, priority) {
  7882. var prevIndex = this._indexOfListener(listener, listenerContext),
  7883. binding;
  7884. if (prevIndex !== -1) {
  7885. binding = this._bindings[prevIndex];
  7886. if (binding.isOnce() !== isOnce) {
  7887. throw new Error('You cannot add'+ (isOnce? '' : 'Once') +'() then add'+ (!isOnce? '' : 'Once') +'() the same listener without removing the relationship first.');
  7888. }
  7889. } else {
  7890. binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority);
  7891. this._addBinding(binding);
  7892. }
  7893. if (this.memorize && this._prevParams){
  7894. binding.execute(this._prevParams);
  7895. }
  7896. return binding;
  7897. },
  7898. /**
  7899. * @method Phaser.Signal#_addBinding
  7900. * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener.
  7901. * @private
  7902. */
  7903. _addBinding: function (binding) {
  7904. //simplified insertion sort
  7905. var n = this._bindings.length;
  7906. do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
  7907. this._bindings.splice(n + 1, 0, binding);
  7908. },
  7909. /**
  7910. * @method Phaser.Signal#_indexOfListener
  7911. * @param {function} listener - Signal handler function.
  7912. * @return {number} Description.
  7913. * @private
  7914. */
  7915. _indexOfListener: function (listener, context) {
  7916. var n = this._bindings.length,
  7917. cur;
  7918. while (n--) {
  7919. cur = this._bindings[n];
  7920. if (cur._listener === listener && cur.context === context) {
  7921. return n;
  7922. }
  7923. }
  7924. return -1;
  7925. },
  7926. /**
  7927. * Check if listener was attached to Signal.
  7928. *
  7929. * @method Phaser.Signal#has
  7930. * @param {Function} listener - Signal handler function.
  7931. * @param {Object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  7932. * @return {boolean} If Signal has the specified listener.
  7933. */
  7934. has: function (listener, context) {
  7935. return this._indexOfListener(listener, context) !== -1;
  7936. },
  7937. /**
  7938. * Add a listener to the signal.
  7939. *
  7940. * @method Phaser.Signal#add
  7941. * @param {function} listener - Signal handler function.
  7942. * @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  7943. * @param {number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0).
  7944. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  7945. */
  7946. add: function (listener, listenerContext, priority) {
  7947. this.validateListener(listener, 'add');
  7948. return this._registerListener(listener, false, listenerContext, priority);
  7949. },
  7950. /**
  7951. * Add listener to the signal that should be removed after first execution (will be executed only once).
  7952. *
  7953. * @method Phaser.Signal#addOnce
  7954. * @param {function} listener Signal handler function.
  7955. * @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  7956. * @param {number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
  7957. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  7958. */
  7959. addOnce: function (listener, listenerContext, priority) {
  7960. this.validateListener(listener, 'addOnce');
  7961. return this._registerListener(listener, true, listenerContext, priority);
  7962. },
  7963. /**
  7964. * Remove a single listener from the dispatch queue.
  7965. *
  7966. * @method Phaser.Signal#remove
  7967. * @param {function} listener Handler function that should be removed.
  7968. * @param {object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
  7969. * @return {function} Listener handler function.
  7970. */
  7971. remove: function (listener, context) {
  7972. this.validateListener(listener, 'remove');
  7973. var i = this._indexOfListener(listener, context);
  7974. if (i !== -1)
  7975. {
  7976. this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal
  7977. this._bindings.splice(i, 1);
  7978. }
  7979. return listener;
  7980. },
  7981. /**
  7982. * Remove all listeners from the Signal.
  7983. *
  7984. * @method Phaser.Signal#removeAll
  7985. */
  7986. removeAll: function () {
  7987. var n = this._bindings.length;
  7988. while (n--) {
  7989. this._bindings[n]._destroy();
  7990. }
  7991. this._bindings.length = 0;
  7992. },
  7993. /**
  7994. * Gets the total number of listeneres attached to ths Signal.
  7995. *
  7996. * @method Phaser.Signal#getNumListeners
  7997. * @return {number} Number of listeners attached to the Signal.
  7998. */
  7999. getNumListeners: function () {
  8000. return this._bindings.length;
  8001. },
  8002. /**
  8003. * Stop propagation of the event, blocking the dispatch to next listeners on the queue.
  8004. * IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.
  8005. * @see Signal.prototype.disable
  8006. *
  8007. * @method Phaser.Signal#halt
  8008. */
  8009. halt: function () {
  8010. this._shouldPropagate = false;
  8011. },
  8012. /**
  8013. * Dispatch/Broadcast Signal to all listeners added to the queue.
  8014. *
  8015. * @method Phaser.Signal#dispatch
  8016. * @param {any} [params] - Parameters that should be passed to each handler.
  8017. */
  8018. dispatch: function () {
  8019. if (!this.active)
  8020. {
  8021. return;
  8022. }
  8023. var paramsArr = Array.prototype.slice.call(arguments);
  8024. var n = this._bindings.length;
  8025. var bindings;
  8026. if (this.memorize)
  8027. {
  8028. this._prevParams = paramsArr;
  8029. }
  8030. if (!n)
  8031. {
  8032. // Should come after memorize
  8033. return;
  8034. }
  8035. bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
  8036. this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
  8037. //execute all callbacks until end of the list or until a callback returns `false` or stops propagation
  8038. //reverse loop since listeners with higher priority will be added at the end of the list
  8039. do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
  8040. },
  8041. /**
  8042. * Forget memorized arguments.
  8043. * @see Signal.memorize
  8044. *
  8045. * @method Phaser.Signal#forget
  8046. */
  8047. forget: function(){
  8048. this._prevParams = null;
  8049. },
  8050. /**
  8051. * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
  8052. * IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.
  8053. *
  8054. * @method Phaser.Signal#dispose
  8055. */
  8056. dispose: function () {
  8057. this.removeAll();
  8058. delete this._bindings;
  8059. delete this._prevParams;
  8060. },
  8061. /**
  8062. *
  8063. * @method Phaser.Signal#toString
  8064. * @return {string} String representation of the object.
  8065. */
  8066. toString: function () {
  8067. return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
  8068. }
  8069. };
  8070. /**
  8071. * @author Richard Davey <rich@photonstorm.com>
  8072. * @copyright 2013 Photon Storm Ltd.
  8073. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  8074. */
  8075. /**
  8076. * Phaser.SignalBinding
  8077. *
  8078. * Object that represents a binding between a Signal and a listener function.
  8079. * This is an internal constructor and shouldn't be called by regular users.
  8080. * Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
  8081. *
  8082. * @class Phaser.SignalBinding
  8083. * @name SignalBinding
  8084. * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
  8085. * @constructor
  8086. * @inner
  8087. * @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to.
  8088. * @param {function} listener - Handler function bound to the signal.
  8089. * @param {boolean} isOnce - If binding should be executed just once.
  8090. * @param {object} [listenerContext] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  8091. * @param {number} [priority] - The priority level of the event listener. (default = 0).
  8092. */
  8093. Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority) {
  8094. /**
  8095. * @property {Phaser.Game} _listener - Handler function bound to the signal.
  8096. * @private
  8097. */
  8098. this._listener = listener;
  8099. /**
  8100. * @property {boolean} _isOnce - If binding should be executed just once.
  8101. * @private
  8102. */
  8103. this._isOnce = isOnce;
  8104. /**
  8105. * @property {object|undefined|null} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  8106. * @memberof SignalBinding.prototype
  8107. */
  8108. this.context = listenerContext;
  8109. /**
  8110. * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to.
  8111. * @private
  8112. */
  8113. this._signal = signal;
  8114. /**
  8115. * @property {number} _priority - Listener priority.
  8116. * @private
  8117. */
  8118. this._priority = priority || 0;
  8119. };
  8120. Phaser.SignalBinding.prototype = {
  8121. /**
  8122. * If binding is active and should be executed.
  8123. * @property {boolean} active
  8124. * @default
  8125. */
  8126. active: true,
  8127. /**
  8128. * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters).
  8129. * @property {array|null} params
  8130. * @default
  8131. */
  8132. params: null,
  8133. /**
  8134. * Call listener passing arbitrary parameters.
  8135. * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.
  8136. * @method Phaser.SignalBinding#execute
  8137. * @param {array} [paramsArr] - Array of parameters that should be passed to the listener.
  8138. * @return {any} Value returned by the listener.
  8139. */
  8140. execute: function (paramsArr) {
  8141. var handlerReturn, params;
  8142. if (this.active && !!this._listener)
  8143. {
  8144. params = this.params? this.params.concat(paramsArr) : paramsArr;
  8145. handlerReturn = this._listener.apply(this.context, params);
  8146. if (this._isOnce)
  8147. {
  8148. this.detach();
  8149. }
  8150. }
  8151. return handlerReturn;
  8152. },
  8153. /**
  8154. * Detach binding from signal.
  8155. * alias to: @see mySignal.remove(myBinding.getListener());
  8156. * @method Phaser.SignalBinding#detach
  8157. * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached.
  8158. */
  8159. detach: function () {
  8160. return this.isBound() ? this._signal.remove(this._listener, this.context) : null;
  8161. },
  8162. /**
  8163. * @method Phaser.SignalBinding#isBound
  8164. * @return {boolean} True if binding is still bound to the signal and has a listener.
  8165. */
  8166. isBound: function () {
  8167. return (!!this._signal && !!this._listener);
  8168. },
  8169. /**
  8170. * @method Phaser.SignalBinding#isOnce
  8171. * @return {boolean} If SignalBinding will only be executed once.
  8172. */
  8173. isOnce: function () {
  8174. return this._isOnce;
  8175. },
  8176. /**
  8177. * @method Phaser.SignalBinding#getListener
  8178. * @return {Function} Handler function bound to the signal.
  8179. */
  8180. getListener: function () {
  8181. return this._listener;
  8182. },
  8183. /**
  8184. * @method Phaser.SignalBinding#getSignal
  8185. * @return {Signal} Signal that listener is currently bound to.
  8186. */
  8187. getSignal: function () {
  8188. return this._signal;
  8189. },
  8190. /**
  8191. * @method Phaser.SignalBinding#_destroy
  8192. * Delete instance properties
  8193. * @private
  8194. */
  8195. _destroy: function () {
  8196. delete this._signal;
  8197. delete this._listener;
  8198. delete this.context;
  8199. },
  8200. /**
  8201. * @method Phaser.SignalBinding#toString
  8202. * @return {string} String representation of the object.
  8203. */
  8204. toString: function () {
  8205. return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
  8206. }
  8207. };
  8208. /**
  8209. * @author Richard Davey <rich@photonstorm.com>
  8210. * @copyright 2013 Photon Storm Ltd.
  8211. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  8212. */
  8213. /**
  8214. * This is a base Filter template to use for any Phaser filter development.
  8215. *
  8216. * @class Phaser.Filter
  8217. * @classdesc Phaser - Filter
  8218. * @constructor
  8219. * @param {Phaser.Game} game - A reference to the currently running game.
  8220. * @param {Object} uniforms - Uniform mappings object
  8221. * @param {Array} fragmentSrc - The fragment shader code.
  8222. */
  8223. Phaser.Filter = function (game, uniforms, fragmentSrc) {
  8224. /**
  8225. * @property {Phaser.Game} game - A reference to the currently running game.
  8226. */
  8227. this.game = game;
  8228. /**
  8229. * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER.
  8230. * @default
  8231. */
  8232. this.type = Phaser.WEBGL_FILTER;
  8233. /**
  8234. * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion.
  8235. * For example the blur filter has two passes blurX and blurY.
  8236. * @property {array} passes - An array of filter objects.
  8237. * @private
  8238. */
  8239. this.passes = [this];
  8240. /**
  8241. * @property {boolean} dirty - Internal PIXI var.
  8242. * @default
  8243. */
  8244. this.dirty = true;
  8245. /**
  8246. * @property {number} padding - Internal PIXI var.
  8247. * @default
  8248. */
  8249. this.padding = 0;
  8250. /**
  8251. * @property {object} uniforms - Default uniform mappings.
  8252. */
  8253. this.uniforms = {
  8254. time: { type: '1f', value: 0 },
  8255. resolution: { type: '2f', value: { x: 256, y: 256 }},
  8256. mouse: { type: '2f', value: { x: 0.0, y: 0.0 }}
  8257. };
  8258. /**
  8259. * @property {array} fragmentSrc - The fragment shader code.
  8260. */
  8261. this.fragmentSrc = fragmentSrc || [];
  8262. };
  8263. Phaser.Filter.prototype = {
  8264. /**
  8265. * Should be over-ridden.
  8266. * @method Phaser.Filter#init
  8267. */
  8268. init: function () {
  8269. // This should be over-ridden. Will receive a variable number of arguments.
  8270. },
  8271. /**
  8272. * Set the resolution uniforms on the filter.
  8273. * @method Phaser.Filter#setResolution
  8274. * @param {number} width - The width of the display.
  8275. * @param {number} height - The height of the display.
  8276. */
  8277. setResolution: function (width, height) {
  8278. this.uniforms.resolution.value.x = width;
  8279. this.uniforms.resolution.value.y = height;
  8280. },
  8281. /**
  8282. * Updates the filter.
  8283. * @method Phaser.Filter#update
  8284. * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform.
  8285. */
  8286. update: function (pointer) {
  8287. if (typeof pointer !== 'undefined')
  8288. {
  8289. if (pointer.x > 0)
  8290. {
  8291. this.uniforms.mouse.x = pointer.x.toFixed(2);
  8292. }
  8293. if (pointer.y > 0)
  8294. {
  8295. this.uniforms.mouse.y = pointer.y.toFixed(2);
  8296. }
  8297. }
  8298. this.uniforms.time.value = this.game.time.totalElapsedSeconds();
  8299. },
  8300. /**
  8301. * Clear down this Filter and null out references
  8302. * @method Phaser.Filter#destroy
  8303. */
  8304. destroy: function () {
  8305. this.game = null;
  8306. }
  8307. };
  8308. /**
  8309. * @name Phaser.Filter#width
  8310. * @property {number} width - The width (resolution uniform)
  8311. */
  8312. Object.defineProperty(Phaser.Filter.prototype, 'width', {
  8313. get: function() {
  8314. return this.uniforms.resolution.value.x;
  8315. },
  8316. set: function(value) {
  8317. this.uniforms.resolution.value.x = value;
  8318. }
  8319. });
  8320. /**
  8321. * @name Phaser.Filter#height
  8322. * @property {number} height - The height (resolution uniform)
  8323. */
  8324. Object.defineProperty(Phaser.Filter.prototype, 'height', {
  8325. get: function() {
  8326. return this.uniforms.resolution.value.y;
  8327. },
  8328. set: function(value) {
  8329. this.uniforms.resolution.value.y = value;
  8330. }
  8331. });
  8332. /**
  8333. * @author Richard Davey <rich@photonstorm.com>
  8334. * @copyright 2013 Photon Storm Ltd.
  8335. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  8336. */
  8337. /**
  8338. * This is a base Plugin template to use for any Phaser plugin development.
  8339. *
  8340. * @class Phaser.Plugin
  8341. * @classdesc Phaser - Plugin
  8342. * @constructor
  8343. * @param {Phaser.Game} game - A reference to the currently running game.
  8344. * @param {Any} parent - The object that owns this plugin, usually Phaser.PluginManager.
  8345. */
  8346. Phaser.Plugin = function (game, parent) {
  8347. if (typeof parent === 'undefined') { parent = null; }
  8348. /**
  8349. * @property {Phaser.Game} game - A reference to the currently running game.
  8350. */
  8351. this.game = game;
  8352. /**
  8353. * @property {Any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null.
  8354. */
  8355. this.parent = parent;
  8356. /**
  8357. * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped.
  8358. * @default
  8359. */
  8360. this.active = false;
  8361. /**
  8362. * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped.
  8363. * @default
  8364. */
  8365. this.visible = false;
  8366. /**
  8367. * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method.
  8368. * @default
  8369. */
  8370. this.hasPreUpdate = false;
  8371. /**
  8372. * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method.
  8373. * @default
  8374. */
  8375. this.hasUpdate = false;
  8376. /**
  8377. * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method.
  8378. * @default
  8379. */
  8380. this.hasPostUpdate = false;
  8381. /**
  8382. * @property {boolean} hasRender - A flag to indicate if this plugin has a render method.
  8383. * @default
  8384. */
  8385. this.hasRender = false;
  8386. /**
  8387. * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method.
  8388. * @default
  8389. */
  8390. this.hasPostRender = false;
  8391. };
  8392. Phaser.Plugin.prototype = {
  8393. /**
  8394. * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
  8395. * It is only called if active is set to true.
  8396. * @method Phaser.Plugin#preUpdate
  8397. */
  8398. preUpdate: function () {
  8399. },
  8400. /**
  8401. * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
  8402. * It is only called if active is set to true.
  8403. * @method Phaser.Plugin#update
  8404. */
  8405. update: function () {
  8406. },
  8407. /**
  8408. * Render is called right after the Game Renderer completes, but before the State.render.
  8409. * It is only called if visible is set to true.
  8410. * @method Phaser.Plugin#render
  8411. */
  8412. render: function () {
  8413. },
  8414. /**
  8415. * Post-render is called after the Game Renderer and State.render have run.
  8416. * It is only called if visible is set to true.
  8417. * @method Phaser.Plugin#postRender
  8418. */
  8419. postRender: function () {
  8420. },
  8421. /**
  8422. * Clear down this Plugin and null out references
  8423. * @method Phaser.Plugin#destroy
  8424. */
  8425. destroy: function () {
  8426. this.game = null;
  8427. this.parent = null;
  8428. this.active = false;
  8429. this.visible = false;
  8430. }
  8431. };
  8432. /* jshint newcap: false */
  8433. /**
  8434. * @author Richard Davey <rich@photonstorm.com>
  8435. * @copyright 2013 Photon Storm Ltd.
  8436. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  8437. */
  8438. /**
  8439. * The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins.
  8440. *
  8441. * @class Phaser.PluginManager
  8442. * @classdesc Phaser - PluginManager
  8443. * @constructor
  8444. * @param {Phaser.Game} game - A reference to the currently running game.
  8445. * @param {Description} parent - Description.
  8446. */
  8447. Phaser.PluginManager = function(game, parent) {
  8448. /**
  8449. * @property {Phaser.Game} game - A reference to the currently running game.
  8450. */
  8451. this.game = game;
  8452. /**
  8453. * @property {Description} _parent - Description.
  8454. * @private
  8455. */
  8456. this._parent = parent;
  8457. /**
  8458. * @property {array} plugins - Description.
  8459. */
  8460. this.plugins = [];
  8461. /**
  8462. * @property {array} _pluginsLength - Description.
  8463. * @private
  8464. * @default
  8465. */
  8466. this._pluginsLength = 0;
  8467. };
  8468. Phaser.PluginManager.prototype = {
  8469. /**
  8470. * Add a new Plugin to the PluginManager.
  8471. * The plugin's game and parent reference are set to this game and pluginmanager parent.
  8472. * @method Phaser.PluginManager#add
  8473. * @param {Phaser.Plugin} plugin - Description.
  8474. * @return {Phaser.Plugin} Description.
  8475. */
  8476. add: function (plugin) {
  8477. var result = false;
  8478. // Prototype?
  8479. if (typeof plugin === 'function')
  8480. {
  8481. plugin = new plugin(this.game, this._parent);
  8482. }
  8483. else
  8484. {
  8485. plugin.game = this.game;
  8486. plugin.parent = this._parent;
  8487. }
  8488. // Check for methods now to avoid having to do this every loop
  8489. if (typeof plugin['preUpdate'] === 'function')
  8490. {
  8491. plugin.hasPreUpdate = true;
  8492. result = true;
  8493. }
  8494. if (typeof plugin['update'] === 'function')
  8495. {
  8496. plugin.hasUpdate = true;
  8497. result = true;
  8498. }
  8499. if (typeof plugin['postUpdate'] === 'function')
  8500. {
  8501. plugin.hasPostUpdate = true;
  8502. result = true;
  8503. }
  8504. if (typeof plugin['render'] === 'function')
  8505. {
  8506. plugin.hasRender = true;
  8507. result = true;
  8508. }
  8509. if (typeof plugin['postRender'] === 'function')
  8510. {
  8511. plugin.hasPostRender = true;
  8512. result = true;
  8513. }
  8514. // The plugin must have at least one of the above functions to be added to the PluginManager.
  8515. if (result)
  8516. {
  8517. if (plugin.hasPreUpdate || plugin.hasUpdate || plugin.hasPostUpdate)
  8518. {
  8519. plugin.active = true;
  8520. }
  8521. if (plugin.hasRender || plugin.hasPostRender)
  8522. {
  8523. plugin.visible = true;
  8524. }
  8525. this._pluginsLength = this.plugins.push(plugin);
  8526. // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager
  8527. if (typeof plugin['init'] === 'function')
  8528. {
  8529. plugin.init();
  8530. }
  8531. return plugin;
  8532. }
  8533. else
  8534. {
  8535. return null;
  8536. }
  8537. },
  8538. /**
  8539. * Remove a Plugin from the PluginManager.
  8540. * @method Phaser.PluginManager#remove
  8541. * @param {Phaser.Plugin} plugin - The plugin to be removed.
  8542. */
  8543. remove: function (plugin) {
  8544. if (this._pluginsLength === 0)
  8545. {
  8546. return;
  8547. }
  8548. for (this._p = 0; this._p < this._pluginsLength; this._p++)
  8549. {
  8550. if (this.plugins[this._p] === plugin)
  8551. {
  8552. plugin.destroy();
  8553. this.plugins.splice(this._p, 1);
  8554. this._pluginsLength--;
  8555. return;
  8556. }
  8557. }
  8558. },
  8559. /**
  8560. * Removes all Plugins from the PluginManager.
  8561. * @method Phaser.PluginManager#removeAll
  8562. */
  8563. removeAll: function() {
  8564. for (this._p = 0; this._p < this._pluginsLength; this._p++)
  8565. {
  8566. this.plugins[this._p].destroy();
  8567. }
  8568. this.plugins.length = 0;
  8569. this._pluginsLength = 0;
  8570. },
  8571. /**
  8572. * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
  8573. * It only calls plugins who have active=true.
  8574. *
  8575. * @method Phaser.PluginManager#preUpdate
  8576. */
  8577. preUpdate: function () {
  8578. if (this._pluginsLength === 0)
  8579. {
  8580. return;
  8581. }
  8582. for (this._p = 0; this._p < this._pluginsLength; this._p++)
  8583. {
  8584. if (this.plugins[this._p].active && this.plugins[this._p].hasPreUpdate)
  8585. {
  8586. this.plugins[this._p].preUpdate();
  8587. }
  8588. }
  8589. },
  8590. /**
  8591. * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
  8592. * It only calls plugins who have active=true.
  8593. *
  8594. * @method Phaser.PluginManager#update
  8595. */
  8596. update: function () {
  8597. if (this._pluginsLength === 0)
  8598. {
  8599. return;
  8600. }
  8601. for (this._p = 0; this._p < this._pluginsLength; this._p++)
  8602. {
  8603. if (this.plugins[this._p].active && this.plugins[this._p].hasUpdate)
  8604. {
  8605. this.plugins[this._p].update();
  8606. }
  8607. }
  8608. },
  8609. /**
  8610. * PostUpdate is the last thing to be called before the world render.
  8611. * In particular, it is called after the world postUpdate, which means the camera has been adjusted.
  8612. * It only calls plugins who have active=true.
  8613. *
  8614. * @method Phaser.PluginManager#postUpdate
  8615. */
  8616. postUpdate: function () {
  8617. if (this._pluginsLength === 0)
  8618. {
  8619. return;
  8620. }
  8621. for (this._p = 0; this._p < this._pluginsLength; this._p++)
  8622. {
  8623. if (this.plugins[this._p].active && this.plugins[this._p].hasPostUpdate)
  8624. {
  8625. this.plugins[this._p].postUpdate();
  8626. }
  8627. }
  8628. },
  8629. /**
  8630. * Render is called right after the Game Renderer completes, but before the State.render.
  8631. * It only calls plugins who have visible=true.
  8632. *
  8633. * @method Phaser.PluginManager#render
  8634. */
  8635. render: function () {
  8636. if (this._pluginsLength === 0)
  8637. {
  8638. return;
  8639. }
  8640. for (this._p = 0; this._p < this._pluginsLength; this._p++)
  8641. {
  8642. if (this.plugins[this._p].visible && this.plugins[this._p].hasRender)
  8643. {
  8644. this.plugins[this._p].render();
  8645. }
  8646. }
  8647. },
  8648. /**
  8649. * Post-render is called after the Game Renderer and State.render have run.
  8650. * It only calls plugins who have visible=true.
  8651. *
  8652. * @method Phaser.PluginManager#postRender
  8653. */
  8654. postRender: function () {
  8655. if (this._pluginsLength === 0)
  8656. {
  8657. return;
  8658. }
  8659. for (this._p = 0; this._p < this._pluginsLength; this._p++)
  8660. {
  8661. if (this.plugins[this._p].visible && this.plugins[this._p].hasPostRender)
  8662. {
  8663. this.plugins[this._p].postRender();
  8664. }
  8665. }
  8666. },
  8667. /**
  8668. * Clear down this PluginManager and null out references
  8669. *
  8670. * @method Phaser.PluginManager#destroy
  8671. */
  8672. destroy: function () {
  8673. this.plugins.length = 0;
  8674. this._pluginsLength = 0;
  8675. this.game = null;
  8676. this._parent = null;
  8677. }
  8678. };
  8679. /**
  8680. * @author Richard Davey <rich@photonstorm.com>
  8681. * @copyright 2013 Photon Storm Ltd.
  8682. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  8683. */
  8684. /**
  8685. * The Stage controls the canvas on which everything is displayed. It handles display within the browser,
  8686. * focus handling, game resizing, scaling and the pause, boot and orientation screens.
  8687. *
  8688. * @class Phaser.Stage
  8689. * @constructor
  8690. * @param {Phaser.Game} game - Game reference to the currently running game.
  8691. * @param {number} width - Width of the canvas element.
  8692. * @param {number} height - Height of the canvas element.
  8693. */
  8694. Phaser.Stage = function (game, width, height) {
  8695. /**
  8696. * @property {Phaser.Game} game - A reference to the currently running Game.
  8697. */
  8698. this.game = game;
  8699. /**
  8700. * @property {string} game - Background color of the stage (defaults to black). Set via the public backgroundColor property.
  8701. * @private
  8702. * @default 'rgb(0,0,0)'
  8703. */
  8704. this._backgroundColor = 'rgb(0,0,0)';
  8705. /**
  8706. * @property {Phaser.Point} offset - Get the offset values (for input and other things).
  8707. */
  8708. this.offset = new Phaser.Point();
  8709. /**
  8710. * @property {HTMLCanvasElement} canvas - Reference to the newly created &lt;canvas&gt; element.
  8711. */
  8712. this.canvas = Phaser.Canvas.create(width, height);
  8713. this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
  8714. /**
  8715. * @property {PIXI.Stage} _stage - The Pixi Stage which is hooked to the renderer.
  8716. * @private
  8717. */
  8718. this._stage = new PIXI.Stage(0x000000, false);
  8719. this._stage.name = '_stage_root';
  8720. this._stage.interactive = false;
  8721. /**
  8722. * @property {number} scaleMode - The current scaleMode.
  8723. */
  8724. this.scaleMode = Phaser.StageScaleMode.NO_SCALE;
  8725. /**
  8726. * @property {Phaser.StageScaleMode} scale - The scale of the current running game.
  8727. */
  8728. this.scale = new Phaser.StageScaleMode(this.game, width, height);
  8729. /**
  8730. * @property {number} aspectRatio - Aspect ratio.
  8731. */
  8732. this.aspectRatio = width / height;
  8733. /**
  8734. * @property {number} _nextOffsetCheck - The time to run the next offset check.
  8735. * @private
  8736. */
  8737. this._nextOffsetCheck = 0;
  8738. /**
  8739. * @property {number|false} checkOffsetInterval - The time (in ms) between which the stage should check to see if it has moved.
  8740. * @default
  8741. */
  8742. this.checkOffsetInterval = 2500;
  8743. };
  8744. Phaser.Stage.prototype = {
  8745. /**
  8746. * Initialises the stage and adds the event listeners.
  8747. * @method Phaser.Stage#boot
  8748. * @private
  8749. */
  8750. boot: function () {
  8751. Phaser.Canvas.getOffset(this.canvas, this.offset);
  8752. this.bounds = new Phaser.Rectangle(this.offset.x, this.offset.y, this.game.width, this.game.height);
  8753. var _this = this;
  8754. this._onChange = function (event) {
  8755. return _this.visibilityChange(event);
  8756. }
  8757. Phaser.Canvas.setUserSelect(this.canvas, 'none');
  8758. Phaser.Canvas.setTouchAction(this.canvas, 'none');
  8759. this.backgroundColor = '#000';
  8760. document.addEventListener('visibilitychange', this._onChange, false);
  8761. document.addEventListener('webkitvisibilitychange', this._onChange, false);
  8762. document.addEventListener('pagehide', this._onChange, false);
  8763. document.addEventListener('pageshow', this._onChange, false);
  8764. window.onblur = this._onChange;
  8765. window.onfocus = this._onChange;
  8766. },
  8767. /**
  8768. * Runs Stage processes that need periodic updates, such as the offset checks.
  8769. * @method Phaser.Stage#update
  8770. */
  8771. update: function () {
  8772. if (this.checkOffsetInterval !== false)
  8773. {
  8774. if (this.game.time.now > this._nextOffsetCheck)
  8775. {
  8776. Phaser.Canvas.getOffset(this.canvas, this.offset);
  8777. this._nextOffsetCheck = this.game.time.now + this.checkOffsetInterval;
  8778. }
  8779. }
  8780. },
  8781. /**
  8782. * This method is called when the document visibility is changed.
  8783. * @method Phaser.Stage#visibilityChange
  8784. * @param {Event} event - Its type will be used to decide whether the game should be paused or not.
  8785. */
  8786. visibilityChange: function (event) {
  8787. if (this.disableVisibilityChange)
  8788. {
  8789. return;
  8790. }
  8791. if (event.type == 'pagehide' || event.type == 'blur' || document['hidden'] === true || document['webkitHidden'] === true)
  8792. {
  8793. this.game.paused = true;
  8794. }
  8795. else
  8796. {
  8797. this.game.paused = false;
  8798. }
  8799. }
  8800. };
  8801. /**
  8802. * @name Phaser.Stage#backgroundColor
  8803. * @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000'
  8804. */
  8805. Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", {
  8806. get: function () {
  8807. return this._backgroundColor;
  8808. },
  8809. set: function (color) {
  8810. this._backgroundColor = color;
  8811. if (this.game.transparent === false)
  8812. {
  8813. if (this.game.renderType == Phaser.CANVAS)
  8814. {
  8815. // Set it directly, this allows us to use rgb alpha values in Canvas mode.
  8816. this.game.canvas.style.backgroundColor = color;
  8817. }
  8818. else
  8819. {
  8820. if (typeof color === 'string')
  8821. {
  8822. color = Phaser.Color.hexToRGB(color);
  8823. }
  8824. this._stage.setBackgroundColor(color);
  8825. }
  8826. }
  8827. }
  8828. });
  8829. /**
  8830. * @author Richard Davey <rich@photonstorm.com>
  8831. * @copyright 2013 Photon Storm Ltd.
  8832. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  8833. */
  8834. /**
  8835. * Phaser Group constructor.
  8836. * @class Phaser.Group
  8837. * @classdesc A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  8838. * @constructor
  8839. * @param {Phaser.Game} game - A reference to the currently running game.
  8840. * @param {*} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
  8841. * @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
  8842. * @param {boolean} [useStage=false] - Should the DisplayObjectContainer this Group creates be added to the World (default, false) or direct to the Stage (true).
  8843. */
  8844. Phaser.Group = function (game, parent, name, useStage) {
  8845. if (typeof parent === 'undefined' || typeof parent === null)
  8846. {
  8847. parent = game.world;
  8848. }
  8849. if (typeof useStage === 'undefined')
  8850. {
  8851. useStage = false;
  8852. }
  8853. /**
  8854. * @property {Phaser.Game} game - A reference to the currently running Game.
  8855. */
  8856. this.game = game;
  8857. /**
  8858. * @property {string} name - A name for this Group. Not used internally but useful for debugging.
  8859. */
  8860. this.name = name || 'group';
  8861. if (useStage)
  8862. {
  8863. this._container = this.game.stage._stage;
  8864. }
  8865. else
  8866. {
  8867. this._container = new PIXI.DisplayObjectContainer();
  8868. this._container.name = this.name;
  8869. if (parent)
  8870. {
  8871. if (parent instanceof Phaser.Group)
  8872. {
  8873. parent._container.addChild(this._container);
  8874. parent._container.updateTransform();
  8875. }
  8876. else
  8877. {
  8878. parent.addChild(this._container);
  8879. parent.updateTransform();
  8880. }
  8881. }
  8882. else
  8883. {
  8884. this.game.stage._stage.addChild(this._container);
  8885. this.game.stage._stage.updateTransform();
  8886. }
  8887. }
  8888. /**
  8889. * @property {number} type - Internal Phaser Type value.
  8890. * @protected
  8891. */
  8892. this.type = Phaser.GROUP;
  8893. /**
  8894. * @property {boolean} exists - If exists is true the the Group is updated, otherwise it is skipped.
  8895. * @default
  8896. */
  8897. this.exists = true;
  8898. // Replaces the PIXI.Point with a slightly more flexible one.
  8899. this._container.scale = new Phaser.Point(1, 1);
  8900. /**
  8901. * @property {Phaser.Point} scale - The scale of the Group container.
  8902. */
  8903. this.scale = this._container.scale;
  8904. /**
  8905. * The cursor is a simple way to iterate through the objects in a Group using the Group.next and Group.previous functions.
  8906. * The cursor is set to the first child added to the Group and doesn't change unless you call next, previous or set it directly with Group.cursor.
  8907. * @property {any} cursor - The current display object that the Group cursor is pointing to.
  8908. */
  8909. this.cursor = null;
  8910. };
  8911. /**
  8912. * @constant
  8913. * @type {number}
  8914. */
  8915. Phaser.Group.RETURN_NONE = 0;
  8916. /**
  8917. * @constant
  8918. * @type {number}
  8919. */
  8920. Phaser.Group.RETURN_TOTAL = 1;
  8921. /**
  8922. * @constant
  8923. * @type {number}
  8924. */
  8925. Phaser.Group.RETURN_CHILD = 2;
  8926. /**
  8927. * @constant
  8928. * @type {number}
  8929. */
  8930. Phaser.Group.SORT_ASCENDING = -1;
  8931. /**
  8932. * @constant
  8933. * @type {number}
  8934. */
  8935. Phaser.Group.SORT_DESCENDING = 1;
  8936. Phaser.Group.prototype = {
  8937. /**
  8938. * Adds an existing object to this Group. The object can be an instance of Phaser.Sprite, Phaser.Button or any other display object.
  8939. * The child is automatically added to the top of the Group, so renders on-top of everything else within the Group. If you need to control
  8940. * that then see the addAt method.
  8941. *
  8942. * @see Phaser.Group#create
  8943. * @see Phaser.Group#addAt
  8944. * @method Phaser.Group#add
  8945. * @param {*} child - An instance of Phaser.Sprite, Phaser.Button or any other display object..
  8946. * @return {*} The child that was added to the Group.
  8947. */
  8948. add: function (child) {
  8949. if (child.group !== this)
  8950. {
  8951. child.group = this;
  8952. if (child.events)
  8953. {
  8954. child.events.onAddedToGroup.dispatch(child, this);
  8955. }
  8956. this._container.addChild(child);
  8957. child.updateTransform();
  8958. if (this.cursor === null)
  8959. {
  8960. this.cursor = child;
  8961. }
  8962. }
  8963. return child;
  8964. },
  8965. /**
  8966. * Adds an existing object to this Group. The object can be an instance of Phaser.Sprite, Phaser.Button or any other display object.
  8967. * The child is added to the Group at the location specified by the index value, this allows you to control child ordering.
  8968. *
  8969. * @method Phaser.Group#addAt
  8970. * @param {*} child - An instance of Phaser.Sprite, Phaser.Button or any other display object..
  8971. * @param {number} index - The index within the Group to insert the child to.
  8972. * @return {*} The child that was added to the Group.
  8973. */
  8974. addAt: function (child, index) {
  8975. if (child.group !== this)
  8976. {
  8977. child.group = this;
  8978. if (child.events)
  8979. {
  8980. child.events.onAddedToGroup.dispatch(child, this);
  8981. }
  8982. this._container.addChildAt(child, index);
  8983. child.updateTransform();
  8984. if (this.cursor === null)
  8985. {
  8986. this.cursor = child;
  8987. }
  8988. }
  8989. return child;
  8990. },
  8991. /**
  8992. * Returns the child found at the given index within this Group.
  8993. *
  8994. * @method Phaser.Group#getAt
  8995. * @param {number} index - The index to return the child from.
  8996. * @return {*} The child that was found at the given index.
  8997. */
  8998. getAt: function (index) {
  8999. return this._container.getChildAt(index);
  9000. },
  9001. /**
  9002. * Automatically creates a new Phaser.Sprite object and adds it to the top of this Group.
  9003. * Useful if you don't need to create the Sprite instances before-hand.
  9004. *
  9005. * @method Phaser.Group#create
  9006. * @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the Group.x point.
  9007. * @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the Group.y point.
  9008. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  9009. * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  9010. * @param {boolean} [exists=true] - The default exists state of the Sprite.
  9011. * @return {Phaser.Sprite} The child that was created.
  9012. */
  9013. create: function (x, y, key, frame, exists) {
  9014. if (typeof exists == 'undefined') { exists = true; }
  9015. var child = new Phaser.Sprite(this.game, x, y, key, frame);
  9016. child.group = this;
  9017. child.exists = exists;
  9018. child.visible = exists;
  9019. child.alive = exists;
  9020. if (child.events)
  9021. {
  9022. child.events.onAddedToGroup.dispatch(child, this);
  9023. }
  9024. this._container.addChild(child);
  9025. child.updateTransform();
  9026. if (this.cursor === null)
  9027. {
  9028. this.cursor = child;
  9029. }
  9030. return child;
  9031. },
  9032. /**
  9033. * Automatically creates multiple Phaser.Sprite objects and adds them to the top of this Group.
  9034. * Useful if you need to quickly generate a pool of identical sprites, such as bullets. By default the sprites will be set to not exist
  9035. * and will be positioned at 0, 0 (relative to the Group.x/y)
  9036. *
  9037. * @method Phaser.Group#createMultiple
  9038. * @param {number} quantity - The number of Sprites to create.
  9039. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  9040. * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  9041. * @param {boolean} [exists=false] - The default exists state of the Sprite.
  9042. */
  9043. createMultiple: function (quantity, key, frame, exists) {
  9044. if (typeof exists == 'undefined') { exists = false; }
  9045. for (var i = 0; i < quantity; i++)
  9046. {
  9047. var child = new Phaser.Sprite(this.game, 0, 0, key, frame);
  9048. child.group = this;
  9049. child.exists = exists;
  9050. child.visible = exists;
  9051. child.alive = exists;
  9052. if (child.events)
  9053. {
  9054. child.events.onAddedToGroup.dispatch(child, this);
  9055. }
  9056. this._container.addChild(child);
  9057. child.updateTransform();
  9058. if (this.cursor === null)
  9059. {
  9060. this.cursor = child;
  9061. }
  9062. }
  9063. },
  9064. /**
  9065. * Advances the Group cursor to the next object in the Group. If it's at the end of the Group it wraps around to the first object.
  9066. *
  9067. * @method Phaser.Group#next
  9068. */
  9069. next: function () {
  9070. if (this.cursor)
  9071. {
  9072. // Wrap the cursor?
  9073. if (this.cursor == this._container.last)
  9074. {
  9075. this.cursor = this._container._iNext;
  9076. }
  9077. else
  9078. {
  9079. this.cursor = this.cursor._iNext;
  9080. }
  9081. }
  9082. },
  9083. /**
  9084. * Moves the Group cursor to the previous object in the Group. If it's at the start of the Group it wraps around to the last object.
  9085. *
  9086. * @method Phaser.Group#previous
  9087. */
  9088. previous: function () {
  9089. if (this.cursor)
  9090. {
  9091. // Wrap the cursor?
  9092. if (this.cursor == this._container._iNext)
  9093. {
  9094. this.cursor = this._container.last;
  9095. }
  9096. else
  9097. {
  9098. this.cursor = this.cursor._iPrev;
  9099. }
  9100. }
  9101. },
  9102. childTest: function (prefix, child) {
  9103. var s = prefix + ' next: ';
  9104. if (child._iNext)
  9105. {
  9106. s = s + child._iNext.name;
  9107. }
  9108. else
  9109. {
  9110. s = s + '-null-';
  9111. }
  9112. s = s + ' ' + prefix + ' prev: ';
  9113. if (child._iPrev)
  9114. {
  9115. s = s + child._iPrev.name;
  9116. }
  9117. else
  9118. {
  9119. s = s + '-null-';
  9120. }
  9121. console.log(s);
  9122. },
  9123. swapIndex: function (index1, index2) {
  9124. var child1 = this.getAt(index1);
  9125. var child2 = this.getAt(index2);
  9126. console.log('swapIndex ', index1, ' with ', index2);
  9127. this.swap(child1, child2);
  9128. },
  9129. /**
  9130. * Swaps the position of two children in this Group. Both children must be in this Group.
  9131. * You cannot swap a child with itself, or swap un-parented children, doing so will return false.
  9132. *
  9133. * @method Phaser.Group#swap
  9134. * @param {*} child1 - The first child to swap.
  9135. * @param {*} child2 - The second child to swap.
  9136. * @return {boolean} True if the swap was successful, otherwise false.
  9137. */
  9138. swap: function (child1, child2) {
  9139. if (child1 === child2 || !child1.parent || !child2.parent || child1.group !== this || child2.group !== this)
  9140. {
  9141. return false;
  9142. }
  9143. // Cache the values
  9144. var child1Prev = child1._iPrev;
  9145. var child1Next = child1._iNext;
  9146. var child2Prev = child2._iPrev;
  9147. var child2Next = child2._iNext;
  9148. var endNode = this._container.last._iNext;
  9149. var currentNode = this.game.stage._stage;
  9150. do
  9151. {
  9152. if (currentNode !== child1 && currentNode !== child2)
  9153. {
  9154. if (currentNode.first === child1)
  9155. {
  9156. currentNode.first = child2;
  9157. }
  9158. else if (currentNode.first === child2)
  9159. {
  9160. currentNode.first = child1;
  9161. }
  9162. if (currentNode.last === child1)
  9163. {
  9164. currentNode.last = child2;
  9165. }
  9166. else if (currentNode.last === child2)
  9167. {
  9168. currentNode.last = child1;
  9169. }
  9170. }
  9171. currentNode = currentNode._iNext;
  9172. }
  9173. while (currentNode != endNode)
  9174. if (child1._iNext == child2)
  9175. {
  9176. // This is a downward (A to B) neighbour swap
  9177. child1._iNext = child2Next;
  9178. child1._iPrev = child2;
  9179. child2._iNext = child1;
  9180. child2._iPrev = child1Prev;
  9181. if (child1Prev) { child1Prev._iNext = child2; }
  9182. if (child2Next) { child2Next._iPrev = child1; }
  9183. if (child1.__renderGroup)
  9184. {
  9185. child1.__renderGroup.updateTexture(child1);
  9186. }
  9187. if (child2.__renderGroup)
  9188. {
  9189. child2.__renderGroup.updateTexture(child2);
  9190. }
  9191. return true;
  9192. }
  9193. else if (child2._iNext == child1)
  9194. {
  9195. // This is an upward (B to A) neighbour swap
  9196. child1._iNext = child2;
  9197. child1._iPrev = child2Prev;
  9198. child2._iNext = child1Next;
  9199. child2._iPrev = child1;
  9200. if (child2Prev) { child2Prev._iNext = child1; }
  9201. if (child1Next) { child1Next._iPrev = child2; }
  9202. if (child1.__renderGroup)
  9203. {
  9204. child1.__renderGroup.updateTexture(child1);
  9205. }
  9206. if (child2.__renderGroup)
  9207. {
  9208. child2.__renderGroup.updateTexture(child2);
  9209. }
  9210. return true;
  9211. }
  9212. else
  9213. {
  9214. // Children are far apart
  9215. child1._iNext = child2Next;
  9216. child1._iPrev = child2Prev;
  9217. child2._iNext = child1Next;
  9218. child2._iPrev = child1Prev;
  9219. if (child1Prev) { child1Prev._iNext = child2; }
  9220. if (child1Next) { child1Next._iPrev = child2; }
  9221. if (child2Prev) { child2Prev._iNext = child1; }
  9222. if (child2Next) { child2Next._iPrev = child1; }
  9223. if (child1.__renderGroup)
  9224. {
  9225. child1.__renderGroup.updateTexture(child1);
  9226. }
  9227. if (child2.__renderGroup)
  9228. {
  9229. child2.__renderGroup.updateTexture(child2);
  9230. }
  9231. return true;
  9232. }
  9233. return false;
  9234. },
  9235. /**
  9236. * Brings the given child to the top of this Group so it renders above all other children.
  9237. *
  9238. * @method Phaser.Group#bringToTop
  9239. * @param {*} child - The child to bring to the top of this Group.
  9240. * @return {*} The child that was moved.
  9241. */
  9242. bringToTop: function (child) {
  9243. if (child.group === this)
  9244. {
  9245. this.remove(child);
  9246. this.add(child);
  9247. }
  9248. return child;
  9249. },
  9250. /**
  9251. * Get the index position of the given child in this Group.
  9252. *
  9253. * @method Phaser.Group#getIndex
  9254. * @param {*} child - The child to get the index for.
  9255. * @return {number} The index of the child or -1 if it's not a member of this Group.
  9256. */
  9257. getIndex: function (child) {
  9258. return this._container.children.indexOf(child);
  9259. },
  9260. /**
  9261. * Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group.
  9262. *
  9263. * @method Phaser.Group#replace
  9264. * @param {*} oldChild - The child in this Group that will be replaced.
  9265. * @param {*} newChild - The child to be inserted into this group.
  9266. */
  9267. replace: function (oldChild, newChild) {
  9268. if (!this._container.first._iNext)
  9269. {
  9270. return;
  9271. }
  9272. var index = this.getIndex(oldChild);
  9273. if (index != -1)
  9274. {
  9275. if (newChild.parent !== undefined)
  9276. {
  9277. newChild.events.onRemovedFromGroup.dispatch(newChild, this);
  9278. newChild.parent.removeChild(newChild);
  9279. }
  9280. this._container.removeChild(oldChild);
  9281. this._container.addChildAt(newChild, index);
  9282. newChild.events.onAddedToGroup.dispatch(newChild, this);
  9283. newChild.updateTransform();
  9284. if (this.cursor == oldChild)
  9285. {
  9286. this.cursor = this._container._iNext;
  9287. }
  9288. }
  9289. },
  9290. /**
  9291. * Sets the given property to the given value on the child. The operation controls the assignment of the value.
  9292. *
  9293. * @method Phaser.Group#setProperty
  9294. * @param {*} child - The child to set the property value on.
  9295. * @param {array} key - An array of strings that make up the property that will be set.
  9296. * @param {*} value - The value that will be set.
  9297. * @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
  9298. */
  9299. setProperty: function (child, key, value, operation) {
  9300. operation = operation || 0;
  9301. // As ugly as this approach looks, and although it's limited to a depth of only 4, it's extremely fast.
  9302. // Much faster than a for loop or object iteration. There are no checks, so if the key isn't valid then it'll fail
  9303. // but as you are likely to call this from inner loops that have to perform well, I'll take that trade off.
  9304. // 0 = Equals
  9305. // 1 = Add
  9306. // 2 = Subtract
  9307. // 3 = Multiply
  9308. // 4 = Divide
  9309. var len = key.length;
  9310. if (len == 1)
  9311. {
  9312. if (operation === 0) { child[key[0]] = value; }
  9313. else if (operation == 1) { child[key[0]] += value; }
  9314. else if (operation == 2) { child[key[0]] -= value; }
  9315. else if (operation == 3) { child[key[0]] *= value; }
  9316. else if (operation == 4) { child[key[0]] /= value; }
  9317. }
  9318. else if (len == 2)
  9319. {
  9320. if (operation === 0) { child[key[0]][key[1]] = value; }
  9321. else if (operation == 1) { child[key[0]][key[1]] += value; }
  9322. else if (operation == 2) { child[key[0]][key[1]] -= value; }
  9323. else if (operation == 3) { child[key[0]][key[1]] *= value; }
  9324. else if (operation == 4) { child[key[0]][key[1]] /= value; }
  9325. }
  9326. else if (len == 3)
  9327. {
  9328. if (operation === 0) { child[key[0]][key[1]][key[2]] = value; }
  9329. else if (operation == 1) { child[key[0]][key[1]][key[2]] += value; }
  9330. else if (operation == 2) { child[key[0]][key[1]][key[2]] -= value; }
  9331. else if (operation == 3) { child[key[0]][key[1]][key[2]] *= value; }
  9332. else if (operation == 4) { child[key[0]][key[1]][key[2]] /= value; }
  9333. }
  9334. else if (len == 4)
  9335. {
  9336. if (operation === 0) { child[key[0]][key[1]][key[2]][key[3]] = value; }
  9337. else if (operation == 1) { child[key[0]][key[1]][key[2]][key[3]] += value; }
  9338. else if (operation == 2) { child[key[0]][key[1]][key[2]][key[3]] -= value; }
  9339. else if (operation == 3) { child[key[0]][key[1]][key[2]][key[3]] *= value; }
  9340. else if (operation == 4) { child[key[0]][key[1]][key[2]][key[3]] /= value; }
  9341. }
  9342. // TODO - Deep property scane
  9343. },
  9344. /**
  9345. * This function allows you to quickly set the same property across all children of this Group to a new value.
  9346. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  9347. *
  9348. * @method Phaser.Group#setAll
  9349. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  9350. * @param {*} value - The value that will be set.
  9351. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated.
  9352. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated.
  9353. * @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
  9354. */
  9355. setAll: function (key, value, checkAlive, checkVisible, operation) {
  9356. key = key.split('.');
  9357. if (typeof checkAlive === 'undefined') { checkAlive = false; }
  9358. if (typeof checkVisible === 'undefined') { checkVisible = false; }
  9359. operation = operation || 0;
  9360. if (this._container.children.length > 0 && this._container.first._iNext)
  9361. {
  9362. var currentNode = this._container.first._iNext;
  9363. do
  9364. {
  9365. if ((checkAlive === false || (checkAlive && currentNode.alive)) && (checkVisible === false || (checkVisible && currentNode.visible)))
  9366. {
  9367. this.setProperty(currentNode, key, value, operation);
  9368. }
  9369. currentNode = currentNode._iNext;
  9370. }
  9371. while (currentNode != this._container.last._iNext)
  9372. }
  9373. },
  9374. /**
  9375. * Adds the amount to the given property on all children in this Group.
  9376. * Group.addAll('x', 10) will add 10 to the child.x value.
  9377. *
  9378. * @method Phaser.Group#addAll
  9379. * @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'.
  9380. * @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50.
  9381. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  9382. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  9383. */
  9384. addAll: function (property, amount, checkAlive, checkVisible) {
  9385. this.setAll(property, amount, checkAlive, checkVisible, 1);
  9386. },
  9387. /**
  9388. * Subtracts the amount from the given property on all children in this Group.
  9389. * Group.subAll('x', 10) will minus 10 from the child.x value.
  9390. *
  9391. * @method Phaser.Group#subAll
  9392. * @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'.
  9393. * @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10.
  9394. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  9395. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  9396. */
  9397. subAll: function (property, amount, checkAlive, checkVisible) {
  9398. this.setAll(property, amount, checkAlive, checkVisible, 2);
  9399. },
  9400. /**
  9401. * Multiplies the given property by the amount on all children in this Group.
  9402. * Group.multiplyAll('x', 2) will x2 the child.x value.
  9403. *
  9404. * @method Phaser.Group#multiplyAll
  9405. * @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'.
  9406. * @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20.
  9407. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  9408. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  9409. */
  9410. multiplyAll: function (property, amount, checkAlive, checkVisible) {
  9411. this.setAll(property, amount, checkAlive, checkVisible, 3);
  9412. },
  9413. /**
  9414. * Divides the given property by the amount on all children in this Group.
  9415. * Group.divideAll('x', 2) will half the child.x value.
  9416. *
  9417. * @method Phaser.Group#divideAll
  9418. * @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'.
  9419. * @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50.
  9420. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  9421. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  9422. */
  9423. divideAll: function (property, amount, checkAlive, checkVisible) {
  9424. this.setAll(property, amount, checkAlive, checkVisible, 4);
  9425. },
  9426. /**
  9427. * Calls a function on all of the children that have exists=true in this Group.
  9428. * After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback.
  9429. *
  9430. * @method Phaser.Group#callAllExists
  9431. * @param {function} callback - The function that exists on the children that will be called.
  9432. * @param {boolean} existsValue - Only children with exists=existsValue will be called.
  9433. * @param {...*} parameter - Additional parameters that will be passed to the callback.
  9434. */
  9435. callAllExists: function (callback, existsValue) {
  9436. var args = Array.prototype.splice.call(arguments, 2);
  9437. if (this._container.children.length > 0 && this._container.first._iNext)
  9438. {
  9439. var currentNode = this._container.first._iNext;
  9440. do
  9441. {
  9442. if (currentNode.exists == existsValue && currentNode[callback])
  9443. {
  9444. currentNode[callback].apply(currentNode, args);
  9445. }
  9446. currentNode = currentNode._iNext;
  9447. }
  9448. while (currentNode != this._container.last._iNext)
  9449. }
  9450. },
  9451. /**
  9452. * Calls a function on all of the children that have exists=true in this Group.
  9453. *
  9454. * @method Phaser.Group#callbackFromArray
  9455. * @param {object} child - The object to inspect.
  9456. * @param {array} callback - The array of function names.
  9457. * @param {number} length - The size of the array (pre-calculated in callAll).
  9458. * @protected
  9459. */
  9460. callbackFromArray: function (child, callback, length) {
  9461. // Kinda looks like a Christmas tree
  9462. if (length == 1)
  9463. {
  9464. if (child[callback[0]])
  9465. {
  9466. return child[callback[0]];
  9467. }
  9468. }
  9469. else if (length == 2)
  9470. {
  9471. if (child[callback[0]][callback[1]])
  9472. {
  9473. return child[callback[0]][callback[1]];
  9474. }
  9475. }
  9476. else if (length == 3)
  9477. {
  9478. if (child[callback[0]][callback[1]][callback[2]])
  9479. {
  9480. return child[callback[0]][callback[1]][callback[2]];
  9481. }
  9482. }
  9483. else if (length == 4)
  9484. {
  9485. if (child[callback[0]][callback[1]][callback[2]][callback[3]])
  9486. {
  9487. return child[callback[0]][callback[1]][callback[2]][callback[3]];
  9488. }
  9489. }
  9490. else
  9491. {
  9492. if (child[callback])
  9493. {
  9494. return child[callback];
  9495. }
  9496. }
  9497. return false;
  9498. },
  9499. /**
  9500. * Calls a function on all of the children regardless if they are dead or alive (see callAllExists if you need control over that)
  9501. * After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child.
  9502. *
  9503. * @method Phaser.Group#callAll
  9504. * @param {string} method - A string containing the name of the function that will be called. The function must exist on the child.
  9505. * @param {string} [context=''] - A string containing the context under which the method will be executed. Leave to '' to default to the child.
  9506. * @param {...*} parameter - Additional parameters that will be passed to the method.
  9507. */
  9508. callAll: function (method, context) {
  9509. if (typeof method === 'undefined')
  9510. {
  9511. return;
  9512. }
  9513. // Extract the method into an array
  9514. method = method.split('.');
  9515. var methodLength = method.length;
  9516. if (typeof context === 'undefined')
  9517. {
  9518. context = null;
  9519. }
  9520. else
  9521. {
  9522. // Extract the context into an array
  9523. if (typeof context === 'string')
  9524. {
  9525. context = context.split('.');
  9526. var contextLength = context.length;
  9527. }
  9528. }
  9529. var args = Array.prototype.splice.call(arguments, 2);
  9530. var callback = null;
  9531. var callbackContext = null;
  9532. if (this._container.children.length > 0 && this._container.first._iNext)
  9533. {
  9534. var child = this._container.first._iNext;
  9535. do
  9536. {
  9537. callback = this.callbackFromArray(child, method, methodLength);
  9538. if (context && callback)
  9539. {
  9540. callbackContext = this.callbackFromArray(child, context, contextLength);
  9541. if (callback)
  9542. {
  9543. callback.apply(callbackContext, args);
  9544. }
  9545. }
  9546. else if (callback)
  9547. {
  9548. callback.apply(child, args);
  9549. }
  9550. child = child._iNext;
  9551. }
  9552. while (child != this._container.last._iNext)
  9553. }
  9554. },
  9555. /**
  9556. * Allows you to call your own function on each member of this Group. You must pass the callback and context in which it will run.
  9557. * After the checkExists parameter you can add as many parameters as you like, which will all be passed to the callback along with the child.
  9558. * For example: Group.forEach(awardBonusGold, this, true, 100, 500)
  9559. *
  9560. * @method Phaser.Group#forEach
  9561. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  9562. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  9563. * @param {boolean} checkExists - If set only children with exists=true will be passed to the callback, otherwise all children will be passed.
  9564. */
  9565. forEach: function (callback, callbackContext, checkExists) {
  9566. if (typeof checkExists === 'undefined')
  9567. {
  9568. checkExists = false;
  9569. }
  9570. var args = Array.prototype.splice.call(arguments, 3);
  9571. args.unshift(null);
  9572. if (this._container.children.length > 0 && this._container.first._iNext)
  9573. {
  9574. var currentNode = this._container.first._iNext;
  9575. do
  9576. {
  9577. if (checkExists === false || (checkExists && currentNode.exists))
  9578. {
  9579. args[0] = currentNode;
  9580. callback.apply(callbackContext, args);
  9581. }
  9582. currentNode = currentNode._iNext;
  9583. }
  9584. while (currentNode != this._container.last._iNext);
  9585. }
  9586. },
  9587. /**
  9588. * Allows you to call your own function on each alive member of this Group (where child.alive=true). You must pass the callback and context in which it will run.
  9589. * You can add as many parameters as you like, which will all be passed to the callback along with the child.
  9590. * For example: Group.forEachAlive(causeDamage, this, 500)
  9591. *
  9592. * @method Phaser.Group#forEachAlive
  9593. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  9594. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  9595. */
  9596. forEachExists: function (callback, callbackContext) {
  9597. var args = Array.prototype.splice.call(arguments, 2);
  9598. args.unshift(null);
  9599. this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  9600. },
  9601. /**
  9602. * Allows you to call your own function on each alive member of this Group (where child.alive=true). You must pass the callback and context in which it will run.
  9603. * You can add as many parameters as you like, which will all be passed to the callback along with the child.
  9604. * For example: Group.forEachAlive(causeDamage, this, 500)
  9605. *
  9606. * @method Phaser.Group#forEachAlive
  9607. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  9608. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  9609. */
  9610. forEachAlive: function (callback, callbackContext) {
  9611. var args = Array.prototype.splice.call(arguments, 2);
  9612. args.unshift(null);
  9613. this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  9614. },
  9615. /**
  9616. * Allows you to call your own function on each dead member of this Group (where alive=false). You must pass the callback and context in which it will run.
  9617. * You can add as many parameters as you like, which will all be passed to the callback along with the child.
  9618. * For example: Group.forEachDead(bringToLife, this)
  9619. *
  9620. * @method Phaser.Group#forEachDead
  9621. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  9622. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  9623. */
  9624. forEachDead: function (callback, callbackContext) {
  9625. var args = Array.prototype.splice.call(arguments, 2);
  9626. args.unshift(null);
  9627. this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  9628. },
  9629. /**
  9630. * Call this function to sort the group according to a particular value and order.
  9631. * For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`.
  9632. *
  9633. * @method Phaser.Group#sort
  9634. * @param {string} [index='y'] - The `string` name of the property you want to sort on.
  9635. * @param {number} [order=Phaser.Group.SORT_ASCENDING] - The `Group` constant that defines the sort order. Possible values are Phaser.Group.SORT_ASCENDING and Phaser.Group.SORT_DESCENDING.
  9636. */
  9637. sort: function (index, order) {
  9638. if (typeof index === 'undefined') { index = 'y'; }
  9639. if (typeof order === 'undefined') { order = Phaser.Group.SORT_ASCENDING; }
  9640. var swapped;
  9641. var temp;
  9642. do {
  9643. swapped = false;
  9644. for (var i = 0, len = this._container.children.length - 1; i < len; i++)
  9645. {
  9646. if (order == Phaser.Group.SORT_ASCENDING)
  9647. {
  9648. if (this._container.children[i][index] > this._container.children[i + 1][index])
  9649. {
  9650. this.swap(this.getAt(i), this.getAt(i + 1));
  9651. temp = this._container.children[i];
  9652. this._container.children[i] = this._container.children[i + 1];
  9653. this._container.children[i + 1] = temp;
  9654. swapped = true;
  9655. }
  9656. }
  9657. else
  9658. {
  9659. if (this._container.children[i][index] < this._container.children[i + 1][index])
  9660. {
  9661. this.swap(this.getAt(i), this.getAt(i + 1));
  9662. temp = this._container.children[i];
  9663. this._container.children[i] = this._container.children[i + 1];
  9664. this._container.children[i + 1] = temp;
  9665. swapped = true;
  9666. }
  9667. }
  9668. }
  9669. } while (swapped);
  9670. },
  9671. /**
  9672. * Iterates over the children of the Group. When a child has a property matching key that equals the given value, it is considered as a match.
  9673. * Matched children can be sent to the optional callback, or simply returned or counted.
  9674. * You can add as many callback parameters as you like, which will all be passed to the callback along with the child, after the callbackContext parameter.
  9675. *
  9676. * @method Phaser.Group#iterate
  9677. * @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health'
  9678. * @param {any} value - If child.key === this value it will be considered a match. Note that a strict comparison is used.
  9679. * @param {number} returnType - How to return the data from this method. Either Phaser.Group.RETURN_NONE, Phaser.Group.RETURN_TOTAL or Phaser.Group.RETURN_CHILD.
  9680. * @param {function} [callback=null] - Optional function that will be called on each matching child. Each child of the Group will be passed to it as its first parameter.
  9681. * @param {Object} [callbackContext] - The context in which the function should be called (usually 'this').
  9682. */
  9683. iterate: function (key, value, returnType, callback, callbackContext, args) {
  9684. if (returnType == Phaser.Group.RETURN_TOTAL && this._container.children.length === 0)
  9685. {
  9686. return -1;
  9687. }
  9688. if (typeof callback === 'undefined')
  9689. {
  9690. callback = false;
  9691. }
  9692. var total = 0;
  9693. if (this._container.children.length > 0 && this._container.first._iNext)
  9694. {
  9695. var currentNode = this._container.first._iNext;
  9696. do
  9697. {
  9698. if (currentNode[key] === value)
  9699. {
  9700. total++;
  9701. if (callback)
  9702. {
  9703. args[0] = currentNode;
  9704. callback.apply(callbackContext, args);
  9705. }
  9706. if (returnType == Phaser.Group.RETURN_CHILD)
  9707. {
  9708. return currentNode;
  9709. }
  9710. }
  9711. currentNode = currentNode._iNext;
  9712. }
  9713. while (currentNode != this._container.last._iNext);
  9714. }
  9715. if (returnType == Phaser.Group.RETURN_TOTAL)
  9716. {
  9717. return total;
  9718. }
  9719. else if (returnType == Phaser.Group.RETURN_CHILD)
  9720. {
  9721. return null;
  9722. }
  9723. },
  9724. /**
  9725. * Call this function to retrieve the first object with exists == (the given state) in the Group.
  9726. *
  9727. * @method Phaser.Group#getFirstExists
  9728. * @param {boolean} state - True or false.
  9729. * @return {Any} The first child, or null if none found.
  9730. */
  9731. getFirstExists: function (state) {
  9732. if (typeof state !== 'boolean')
  9733. {
  9734. state = true;
  9735. }
  9736. return this.iterate('exists', state, Phaser.Group.RETURN_CHILD);
  9737. },
  9738. /**
  9739. * Call this function to retrieve the first object with alive === true in the group.
  9740. * This is handy for checking if everything has been wiped out, or choosing a squad leader, etc.
  9741. *
  9742. * @method Phaser.Group#getFirstAlive
  9743. * @return {Any} The first alive child, or null if none found.
  9744. */
  9745. getFirstAlive: function () {
  9746. return this.iterate('alive', true, Phaser.Group.RETURN_CHILD);
  9747. },
  9748. /**
  9749. * Call this function to retrieve the first object with alive === false in the group.
  9750. * This is handy for checking if everything has been wiped out, or choosing a squad leader, etc.
  9751. *
  9752. * @method Phaser.Group#getFirstDead
  9753. * @return {Any} The first dead child, or null if none found.
  9754. */
  9755. getFirstDead: function () {
  9756. return this.iterate('alive', false, Phaser.Group.RETURN_CHILD);
  9757. },
  9758. /**
  9759. * Call this function to find out how many members of the group are alive.
  9760. *
  9761. * @method Phaser.Group#countLiving
  9762. * @return {number} The number of children flagged as alive. Returns -1 if Group is empty.
  9763. */
  9764. countLiving: function () {
  9765. return this.iterate('alive', true, Phaser.Group.RETURN_TOTAL);
  9766. },
  9767. /**
  9768. * Call this function to find out how many members of the group are dead.
  9769. *
  9770. * @method Phaser.Group#countDead
  9771. * @return {number} The number of children flagged as dead. Returns -1 if Group is empty.
  9772. */
  9773. countDead: function () {
  9774. return this.iterate('alive', false, Phaser.Group.RETURN_TOTAL);
  9775. },
  9776. /**
  9777. * Returns a member at random from the group.
  9778. *
  9779. * @method Phaser.Group#getRandom
  9780. * @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
  9781. * @param {number} length - Optional restriction on the number of values you want to randomly select from.
  9782. * @return {Any} A random child of this Group.
  9783. */
  9784. getRandom: function (startIndex, length) {
  9785. if (this._container.children.length === 0)
  9786. {
  9787. return null;
  9788. }
  9789. startIndex = startIndex || 0;
  9790. length = length || this._container.children.length;
  9791. return this.game.math.getRandom(this._container.children, startIndex, length);
  9792. },
  9793. /**
  9794. * Removes the given child from this Group and sets its group property to null.
  9795. *
  9796. * @method Phaser.Group#remove
  9797. * @param {Any} child - The child to remove.
  9798. * @return {boolean} true if the child was removed from this Group, otherwise false.
  9799. */
  9800. remove: function (child) {
  9801. if (child.group !== this)
  9802. {
  9803. return false;
  9804. }
  9805. if (child.events)
  9806. {
  9807. child.events.onRemovedFromGroup.dispatch(child, this);
  9808. }
  9809. // Check it's actually in the container
  9810. if (child.parent === this._container)
  9811. {
  9812. this._container.removeChild(child);
  9813. }
  9814. if (this.cursor == child)
  9815. {
  9816. if (this._container._iNext)
  9817. {
  9818. this.cursor = this._container._iNext;
  9819. }
  9820. else
  9821. {
  9822. this.cursor = null;
  9823. }
  9824. }
  9825. child.group = null;
  9826. return true;
  9827. },
  9828. /**
  9829. * Removes all children from this Group, setting all group properties to null.
  9830. * The Group container remains on the display list.
  9831. *
  9832. * @method Phaser.Group#removeAll
  9833. */
  9834. removeAll: function () {
  9835. if (this._container.children.length === 0)
  9836. {
  9837. return;
  9838. }
  9839. do
  9840. {
  9841. if (this._container.children[0].events)
  9842. {
  9843. this._container.children[0].events.onRemovedFromGroup.dispatch(this._container.children[0], this);
  9844. }
  9845. this._container.removeChild(this._container.children[0]);
  9846. }
  9847. while (this._container.children.length > 0);
  9848. this.cursor = null;
  9849. },
  9850. /**
  9851. * Removes all children from this Group whos index falls beteen the given startIndex and endIndex values.
  9852. *
  9853. * @method Phaser.Group#removeBetween
  9854. * @param {number} startIndex - The index to start removing children from.
  9855. * @param {number} endIndex - The index to stop removing children from. Must be higher than startIndex and less than the length of the Group.
  9856. */
  9857. removeBetween: function (startIndex, endIndex) {
  9858. if (this._container.children.length === 0)
  9859. {
  9860. return;
  9861. }
  9862. if (startIndex > endIndex || startIndex < 0 || endIndex > this._container.children.length)
  9863. {
  9864. return false;
  9865. }
  9866. for (var i = startIndex; i < endIndex; i++)
  9867. {
  9868. var child = this._container.children[i];
  9869. child.events.onRemovedFromGroup.dispatch(child, this);
  9870. this._container.removeChild(child);
  9871. if (this.cursor == child)
  9872. {
  9873. if (this._container._iNext)
  9874. {
  9875. this.cursor = this._container._iNext;
  9876. }
  9877. else
  9878. {
  9879. this.cursor = null;
  9880. }
  9881. }
  9882. }
  9883. },
  9884. /**
  9885. * Destroys this Group. Removes all children, then removes the container from the display list and nulls references.
  9886. *
  9887. * @method Phaser.Group#destroy
  9888. */
  9889. destroy: function () {
  9890. this.removeAll();
  9891. if (this._container.parent) this._container.parent.removeChild(this._container);
  9892. this._container = null;
  9893. this.game = null;
  9894. this.exists = false;
  9895. this.cursor = null;
  9896. },
  9897. validate: function () {
  9898. var testObject = this.game.stage._stage.last._iNext;
  9899. var displayObject = this.game.stage._stage;
  9900. var nextObject = null;
  9901. var prevObject = null;
  9902. var count = 0;
  9903. do
  9904. {
  9905. if (count > 0)
  9906. {
  9907. // check next
  9908. if (displayObject !== nextObject)
  9909. {
  9910. console.log('check next fail');
  9911. return false;
  9912. }
  9913. // check previous
  9914. if (displayObject._iPrev !== prevObject)
  9915. {
  9916. console.log('check previous fail');
  9917. return false;
  9918. }
  9919. }
  9920. // Set the next object
  9921. nextObject = displayObject._iNext;
  9922. prevObject = displayObject;
  9923. displayObject = displayObject._iNext;
  9924. count++;
  9925. }
  9926. while(displayObject != testObject)
  9927. return true;
  9928. },
  9929. /**
  9930. * Dumps out a list of Group children and their index positions to the browser console. Useful for group debugging.
  9931. *
  9932. * @method Phaser.Group#dump
  9933. * @param {boolean} [full=false] - If full the dump will include the entire display list, start from the Stage. Otherwise it will only include this container.
  9934. */
  9935. dump: function (full) {
  9936. if (typeof full == 'undefined')
  9937. {
  9938. full = false;
  9939. }
  9940. var spacing = 20;
  9941. var output = "\n" + Phaser.Utils.pad('Node', spacing) + "|" + Phaser.Utils.pad('Next', spacing) + "|" + Phaser.Utils.pad('Previous', spacing) + "|" + Phaser.Utils.pad('First', spacing) + "|" + Phaser.Utils.pad('Last', spacing);
  9942. console.log(output);
  9943. var output = Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing);
  9944. console.log(output);
  9945. if (full)
  9946. {
  9947. var testObject = this.game.stage._stage.last._iNext;
  9948. var displayObject = this.game.stage._stage;
  9949. }
  9950. else
  9951. {
  9952. var testObject = this._container.last._iNext;
  9953. var displayObject = this._container;
  9954. }
  9955. do
  9956. {
  9957. var name = displayObject.name || '*';
  9958. if (this.cursor == displayObject)
  9959. {
  9960. var name = '> ' + name;
  9961. }
  9962. var nameNext = '-';
  9963. var namePrev = '-';
  9964. var nameFirst = '-';
  9965. var nameLast = '-';
  9966. if (displayObject._iNext)
  9967. {
  9968. nameNext = displayObject._iNext.name;
  9969. }
  9970. if (displayObject._iPrev)
  9971. {
  9972. namePrev = displayObject._iPrev.name;
  9973. }
  9974. if (displayObject.first)
  9975. {
  9976. nameFirst = displayObject.first.name;
  9977. }
  9978. if (displayObject.last)
  9979. {
  9980. nameLast = displayObject.last.name;
  9981. }
  9982. if (typeof nameNext === 'undefined')
  9983. {
  9984. nameNext = '-';
  9985. }
  9986. if (typeof namePrev === 'undefined')
  9987. {
  9988. namePrev = '-';
  9989. }
  9990. if (typeof nameFirst === 'undefined')
  9991. {
  9992. nameFirst = '-';
  9993. }
  9994. if (typeof nameLast === 'undefined')
  9995. {
  9996. nameLast = '-';
  9997. }
  9998. var output = Phaser.Utils.pad(name, spacing) + "|" + Phaser.Utils.pad(nameNext, spacing) + "|" + Phaser.Utils.pad(namePrev, spacing) + "|" + Phaser.Utils.pad(nameFirst, spacing) + "|" + Phaser.Utils.pad(nameLast, spacing);
  9999. console.log(output);
  10000. displayObject = displayObject._iNext;
  10001. }
  10002. while(displayObject != testObject)
  10003. }
  10004. };
  10005. /**
  10006. * @name Phaser.Group#total
  10007. * @property {number} total - The total number of children in this Group, regardless of their alive state.
  10008. * @readonly
  10009. */
  10010. Object.defineProperty(Phaser.Group.prototype, "total", {
  10011. get: function () {
  10012. return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL);
  10013. // return this._container.children.length;
  10014. }
  10015. });
  10016. /**
  10017. * @name Phaser.Group#length
  10018. * @property {number} length - The number of children in this Group.
  10019. * @readonly
  10020. */
  10021. Object.defineProperty(Phaser.Group.prototype, "length", {
  10022. get: function () {
  10023. return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL);
  10024. // return this._container.children.length;
  10025. }
  10026. });
  10027. /**
  10028. * The x coordinate of the Group container. You can adjust the Group container itself by modifying its coordinates.
  10029. * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
  10030. * @name Phaser.Group#x
  10031. * @property {number} x - The x coordinate of the Group container.
  10032. */
  10033. Object.defineProperty(Phaser.Group.prototype, "x", {
  10034. get: function () {
  10035. return this._container.position.x;
  10036. },
  10037. set: function (value) {
  10038. this._container.position.x = value;
  10039. }
  10040. });
  10041. /**
  10042. * The y coordinate of the Group container. You can adjust the Group container itself by modifying its coordinates.
  10043. * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
  10044. * @name Phaser.Group#y
  10045. * @property {number} y - The y coordinate of the Group container.
  10046. */
  10047. Object.defineProperty(Phaser.Group.prototype, "y", {
  10048. get: function () {
  10049. return this._container.position.y;
  10050. },
  10051. set: function (value) {
  10052. this._container.position.y = value;
  10053. }
  10054. });
  10055. /**
  10056. * The angle of rotation of the Group container. This will adjust the Group container itself by modifying its rotation.
  10057. * This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
  10058. * @name Phaser.Group#angle
  10059. * @property {number} angle - The angle of rotation given in degrees, where 0 degrees = to the right.
  10060. */
  10061. Object.defineProperty(Phaser.Group.prototype, "angle", {
  10062. get: function() {
  10063. return Phaser.Math.radToDeg(this._container.rotation);
  10064. },
  10065. set: function(value) {
  10066. this._container.rotation = Phaser.Math.degToRad(value);
  10067. }
  10068. });
  10069. /**
  10070. * The angle of rotation of the Group container. This will adjust the Group container itself by modifying its rotation.
  10071. * This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
  10072. * @name Phaser.Group#rotation
  10073. * @property {number} rotation - The angle of rotation given in radians.
  10074. */
  10075. Object.defineProperty(Phaser.Group.prototype, "rotation", {
  10076. get: function () {
  10077. return this._container.rotation;
  10078. },
  10079. set: function (value) {
  10080. this._container.rotation = value;
  10081. }
  10082. });
  10083. /**
  10084. * @name Phaser.Group#visible
  10085. * @property {boolean} visible - The visible state of the Group. Non-visible Groups and all of their children are not rendered.
  10086. */
  10087. Object.defineProperty(Phaser.Group.prototype, "visible", {
  10088. get: function () {
  10089. return this._container.visible;
  10090. },
  10091. set: function (value) {
  10092. this._container.visible = value;
  10093. }
  10094. });
  10095. /**
  10096. * @name Phaser.Group#alpha
  10097. * @property {number} alpha - The alpha value of the Group container.
  10098. */
  10099. Object.defineProperty(Phaser.Group.prototype, "alpha", {
  10100. get: function () {
  10101. return this._container.alpha;
  10102. },
  10103. set: function (value) {
  10104. this._container.alpha = value;
  10105. }
  10106. });
  10107. /**
  10108. * @author Richard Davey <rich@photonstorm.com>
  10109. * @copyright 2013 Photon Storm Ltd.
  10110. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  10111. */
  10112. /**
  10113. * "This world is but a canvas to our imagination." - Henry David Thoreau
  10114. *
  10115. * A game has only one world. The world is an abstract place in which all game objects live. It is not bound
  10116. * by stage limits and can be any size. You look into the world via cameras. All game objects live within
  10117. * the world at world-based coordinates. By default a world is created the same size as your Stage.
  10118. *
  10119. * @class Phaser.World
  10120. * @constructor
  10121. * @param {Phaser.Game} game - Reference to the current game instance.
  10122. */
  10123. Phaser.World = function (game) {
  10124. Phaser.Group.call(this, game, null, '__world', false);
  10125. /**
  10126. * @property {Phaser.Point} scale - Replaces the PIXI.Point with a slightly more flexible one.
  10127. */
  10128. this.scale = new Phaser.Point(1, 1);
  10129. /**
  10130. * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects.
  10131. * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display.
  10132. * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0.
  10133. * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0.
  10134. * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from.
  10135. */
  10136. this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height);
  10137. /**
  10138. * @property {Phaser.Camera} camera - Camera instance.
  10139. */
  10140. this.camera = null;
  10141. /**
  10142. * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated.
  10143. */
  10144. this.currentRenderOrderID = 0;
  10145. };
  10146. Phaser.World.prototype = Object.create(Phaser.Group.prototype);
  10147. Phaser.World.prototype.constructor = Phaser.World;
  10148. /**
  10149. * Initialises the game world.
  10150. *
  10151. * @method Phaser.World#boot
  10152. * @protected
  10153. */
  10154. Phaser.World.prototype.boot = function () {
  10155. this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height);
  10156. this.camera.displayObject = this._container;
  10157. this.game.camera = this.camera;
  10158. }
  10159. /**
  10160. * This is called automatically every frame, and is where main logic happens.
  10161. *
  10162. * @method Phaser.World#update
  10163. */
  10164. Phaser.World.prototype.update = function () {
  10165. this.currentRenderOrderID = 0;
  10166. if (this.game.stage._stage.first._iNext)
  10167. {
  10168. var currentNode = this.game.stage._stage.first._iNext;
  10169. var skipChildren;
  10170. do
  10171. {
  10172. skipChildren = false;
  10173. if (currentNode['preUpdate'])
  10174. {
  10175. skipChildren = (currentNode.preUpdate() === false);
  10176. }
  10177. if (currentNode['update'])
  10178. {
  10179. skipChildren = (currentNode.update() === false) || skipChildren;
  10180. }
  10181. if (skipChildren)
  10182. {
  10183. currentNode = currentNode.last._iNext;
  10184. }
  10185. else
  10186. {
  10187. currentNode = currentNode._iNext;
  10188. }
  10189. }
  10190. while (currentNode != this.game.stage._stage.last._iNext)
  10191. }
  10192. }
  10193. /**
  10194. * This is called automatically every frame, and is where main logic happens.
  10195. * @method Phaser.World#postUpdate
  10196. */
  10197. Phaser.World.prototype.postUpdate = function () {
  10198. if (this.game.stage._stage.first._iNext)
  10199. {
  10200. var currentNode = this.game.stage._stage.first._iNext;
  10201. do
  10202. {
  10203. if (currentNode['postUpdate'])
  10204. {
  10205. currentNode.postUpdate();
  10206. }
  10207. currentNode = currentNode._iNext;
  10208. }
  10209. while (currentNode != this.game.stage._stage.last._iNext)
  10210. }
  10211. this.camera.update();
  10212. }
  10213. /**
  10214. * Updates the size of this world. Note that this doesn't modify the world x/y coordinates, just the width and height.
  10215. * If you need to adjust the bounds of the world
  10216. * @method Phaser.World#setBounds
  10217. * @param {number} x - Top left most corner of the world.
  10218. * @param {number} y - Top left most corner of the world.
  10219. * @param {number} width - New width of the world.
  10220. * @param {number} height - New height of the world.
  10221. */
  10222. Phaser.World.prototype.setBounds = function (x, y, width, height) {
  10223. this.bounds.setTo(x, y, width, height);
  10224. if (this.camera.bounds)
  10225. {
  10226. this.camera.bounds.setTo(x, y, width, height);
  10227. }
  10228. }
  10229. /**
  10230. * Destroyer of worlds.
  10231. * @method Phaser.World#destroy
  10232. */
  10233. Phaser.World.prototype.destroy = function () {
  10234. this.camera.x = 0;
  10235. this.camera.y = 0;
  10236. this.game.input.reset(true);
  10237. this.removeAll();
  10238. }
  10239. /**
  10240. * @name Phaser.World#width
  10241. * @property {number} width - Gets or sets the current width of the game world.
  10242. */
  10243. Object.defineProperty(Phaser.World.prototype, "width", {
  10244. get: function () {
  10245. return this.bounds.width;
  10246. },
  10247. set: function (value) {
  10248. this.bounds.width = value;
  10249. }
  10250. });
  10251. /**
  10252. * @name Phaser.World#height
  10253. * @property {number} height - Gets or sets the current height of the game world.
  10254. */
  10255. Object.defineProperty(Phaser.World.prototype, "height", {
  10256. get: function () {
  10257. return this.bounds.height;
  10258. },
  10259. set: function (value) {
  10260. this.bounds.height = value;
  10261. }
  10262. });
  10263. /**
  10264. * @name Phaser.World#centerX
  10265. * @property {number} centerX - Gets the X position corresponding to the center point of the world.
  10266. * @readonly
  10267. */
  10268. Object.defineProperty(Phaser.World.prototype, "centerX", {
  10269. get: function () {
  10270. return this.bounds.halfWidth;
  10271. }
  10272. });
  10273. /**
  10274. * @name Phaser.World#centerY
  10275. * @property {number} centerY - Gets the Y position corresponding to the center point of the world.
  10276. * @readonly
  10277. */
  10278. Object.defineProperty(Phaser.World.prototype, "centerY", {
  10279. get: function () {
  10280. return this.bounds.halfHeight;
  10281. }
  10282. });
  10283. /**
  10284. * @name Phaser.World#randomX
  10285. * @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world.
  10286. * @readonly
  10287. */
  10288. Object.defineProperty(Phaser.World.prototype, "randomX", {
  10289. get: function () {
  10290. if (this.bounds.x < 0)
  10291. {
  10292. return this.game.rnd.integerInRange(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x)));
  10293. }
  10294. else
  10295. {
  10296. return this.game.rnd.integerInRange(this.bounds.x, this.bounds.width);
  10297. }
  10298. }
  10299. });
  10300. /**
  10301. * @name Phaser.World#randomY
  10302. * @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world.
  10303. * @readonly
  10304. */
  10305. Object.defineProperty(Phaser.World.prototype, "randomY", {
  10306. get: function () {
  10307. if (this.bounds.y < 0)
  10308. {
  10309. return this.game.rnd.integerInRange(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y)));
  10310. }
  10311. else
  10312. {
  10313. return this.game.rnd.integerInRange(this.bounds.y, this.bounds.height);
  10314. }
  10315. }
  10316. });
  10317. /**
  10318. * @name Phaser.World#visible
  10319. * @property {boolean} visible - Gets or sets the visible state of the World.
  10320. */
  10321. Object.defineProperty(Phaser.World.prototype, "visible", {
  10322. get: function () {
  10323. return this._container.visible;
  10324. },
  10325. set: function (value) {
  10326. this._container.visible = value;
  10327. }
  10328. });
  10329. /**
  10330. * @author Richard Davey <rich@photonstorm.com>
  10331. * @copyright 2013 Photon Storm Ltd.
  10332. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  10333. */
  10334. /**
  10335. * Game constructor
  10336. *
  10337. * Instantiate a new <code>Phaser.Game</code> object.
  10338. * @class Phaser.Game
  10339. * @classdesc This is where the magic happens. The Game object is the heart of your game,
  10340. * providing quick access to common functions and handling the boot process.
  10341. * "Hell, there are no rules here - we're trying to accomplish something."
  10342. * Thomas A. Edison
  10343. * @constructor
  10344. * @param {number} [width=800] - The width of your game in game pixels.
  10345. * @param {number} [height=600] - The height of your game in game pixels.
  10346. * @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all).
  10347. * @param {HTMLElement} [parent=''] - The Games DOM parent.
  10348. * @param {any} [state=null] - Description.
  10349. * @param {boolean} [transparent=false] - Use a transparent canvas background or not.
  10350. * @param {boolean} [antialias=true] - Anti-alias graphics.
  10351. */
  10352. Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias) {
  10353. width = width || 800;
  10354. height = height || 600;
  10355. renderer = renderer || Phaser.AUTO;
  10356. parent = parent || '';
  10357. state = state || null;
  10358. if (typeof transparent == 'undefined') { transparent = false; }
  10359. if (typeof antialias == 'undefined') { antialias = true; }
  10360. /**
  10361. * @property {number} id - Phaser Game ID (for when Pixi supports multiple instances).
  10362. */
  10363. this.id = Phaser.GAMES.push(this) - 1;
  10364. /**
  10365. * @property {HTMLElement} parent - The Games DOM parent.
  10366. */
  10367. this.parent = parent;
  10368. // Do some more intelligent size parsing here, so they can set "100%" for example, maybe pass the scale mode in here too?
  10369. /**
  10370. * @property {number} width - The Game width (in pixels).
  10371. */
  10372. this.width = width;
  10373. /**
  10374. * @property {number} height - The Game height (in pixels).
  10375. */
  10376. this.height = height;
  10377. /**
  10378. * @property {boolean} transparent - Use a transparent canvas background or not.
  10379. */
  10380. this.transparent = transparent;
  10381. /**
  10382. * @property {boolean} antialias - Anti-alias graphics (in WebGL this helps with edges, in Canvas2D it retains pixel-art quality).
  10383. */
  10384. this.antialias = antialias;
  10385. /**
  10386. * @property {number} renderer - The Pixi Renderer
  10387. * @default
  10388. */
  10389. this.renderer = null;
  10390. /**
  10391. * @property {number} state - The StateManager.
  10392. */
  10393. this.state = new Phaser.StateManager(this, state);
  10394. /**
  10395. * @property {boolean} _paused - Is game paused?
  10396. * @private
  10397. * @default
  10398. */
  10399. this._paused = false;
  10400. /**
  10401. * @property {number} renderType - The Renderer this Phaser.Game will use. Either Phaser.RENDERER_AUTO, Phaser.RENDERER_CANVAS or Phaser.RENDERER_WEBGL.
  10402. */
  10403. this.renderType = renderer;
  10404. /**
  10405. * @property {boolean} _loadComplete - Whether load complete loading or not.
  10406. * @private
  10407. * @default
  10408. */
  10409. this._loadComplete = false;
  10410. /**
  10411. * @property {boolean} isBooted - Whether the game engine is booted, aka available.
  10412. * @default
  10413. */
  10414. this.isBooted = false;
  10415. /**
  10416. * @property {boolean} id -Is game running or paused?
  10417. * @default
  10418. */
  10419. this.isRunning = false;
  10420. /**
  10421. * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
  10422. * @default
  10423. */
  10424. this.raf = null;
  10425. /**
  10426. * @property {Phaser.GameObjectFactory} add - Reference to the GameObject Factory.
  10427. * @default
  10428. */
  10429. this.add = null;
  10430. /**
  10431. * @property {Phaser.Cache} cache - Reference to the assets cache.
  10432. * @default
  10433. */
  10434. this.cache = null;
  10435. /**
  10436. * @property {Phaser.Input} input - Reference to the input manager
  10437. * @default
  10438. */
  10439. this.input = null;
  10440. /**
  10441. * @property {Phaser.Loader} load - Reference to the assets loader.
  10442. * @default
  10443. */
  10444. this.load = null;
  10445. /**
  10446. * @property {Phaser.Math} math - Reference to the math helper.
  10447. * @default
  10448. */
  10449. this.math = null;
  10450. /**
  10451. * @property {Phaser.Net} net - Reference to the network class.
  10452. * @default
  10453. */
  10454. this.net = null;
  10455. /**
  10456. * @property {Phaser.SoundManager} sound - Reference to the sound manager.
  10457. * @default
  10458. */
  10459. this.sound = null;
  10460. /**
  10461. * @property {Phaser.Stage} stage - Reference to the stage.
  10462. * @default
  10463. */
  10464. this.stage = null;
  10465. /**
  10466. * @property {Phaser.TimeManager} time - Reference to game clock.
  10467. * @default
  10468. */
  10469. this.time = null;
  10470. /**
  10471. * @property {Phaser.TweenManager} tweens - Reference to the tween manager.
  10472. * @default
  10473. */
  10474. this.tweens = null;
  10475. /**
  10476. * @property {Phaser.World} world - Reference to the world.
  10477. * @default
  10478. */
  10479. this.world = null;
  10480. /**
  10481. * @property {Phaser.Physics.PhysicsManager} physics - Reference to the physics manager.
  10482. * @default
  10483. */
  10484. this.physics = null;
  10485. /**
  10486. * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
  10487. * @default
  10488. */
  10489. this.rnd = null;
  10490. /**
  10491. * @property {Phaser.Device} device - Contains device information and capabilities.
  10492. * @default
  10493. */
  10494. this.device = null;
  10495. /**
  10496. * @property {Phaser.Physics.PhysicsManager} camera - A handy reference to world.camera.
  10497. * @default
  10498. */
  10499. this.camera = null;
  10500. /**
  10501. * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view.
  10502. * @default
  10503. */
  10504. this.canvas = null;
  10505. /**
  10506. * @property {Context} context - A handy reference to renderer.context (only set for CANVAS games)
  10507. * @default
  10508. */
  10509. this.context = null;
  10510. /**
  10511. * @property {Phaser.Utils.Debug} debug - A set of useful debug utilitie.
  10512. * @default
  10513. */
  10514. this.debug = null;
  10515. /**
  10516. * @property {Phaser.Particles} particles - The Particle Manager.
  10517. * @default
  10518. */
  10519. this.particles = null;
  10520. var _this = this;
  10521. this._onBoot = function () {
  10522. return _this.boot();
  10523. }
  10524. if (document.readyState === 'complete' || document.readyState === 'interactive')
  10525. {
  10526. window.setTimeout(this._onBoot, 0);
  10527. }
  10528. else
  10529. {
  10530. document.addEventListener('DOMContentLoaded', this._onBoot, false);
  10531. window.addEventListener('load', this._onBoot, false);
  10532. }
  10533. return this;
  10534. };
  10535. Phaser.Game.prototype = {
  10536. /**
  10537. * Initialize engine sub modules and start the game.
  10538. *
  10539. * @method Phaser.Game#boot
  10540. * @protected
  10541. */
  10542. boot: function () {
  10543. if (this.isBooted)
  10544. {
  10545. return;
  10546. }
  10547. if (!document.body)
  10548. {
  10549. window.setTimeout(this._onBoot, 20);
  10550. }
  10551. else
  10552. {
  10553. document.removeEventListener('DOMContentLoaded', this._onBoot);
  10554. window.removeEventListener('load', this._onBoot);
  10555. this.onPause = new Phaser.Signal();
  10556. this.onResume = new Phaser.Signal();
  10557. this.isBooted = true;
  10558. this.device = new Phaser.Device();
  10559. this.math = Phaser.Math;
  10560. this.rnd = new Phaser.RandomDataGenerator([(Date.now() * Math.random()).toString()]);
  10561. this.stage = new Phaser.Stage(this, this.width, this.height);
  10562. this.setUpRenderer();
  10563. this.world = new Phaser.World(this);
  10564. this.add = new Phaser.GameObjectFactory(this);
  10565. this.cache = new Phaser.Cache(this);
  10566. this.load = new Phaser.Loader(this);
  10567. this.time = new Phaser.Time(this);
  10568. this.tweens = new Phaser.TweenManager(this);
  10569. this.input = new Phaser.Input(this);
  10570. this.sound = new Phaser.SoundManager(this);
  10571. this.physics = new Phaser.Physics.Arcade(this);
  10572. this.particles = new Phaser.Particles(this);
  10573. this.plugins = new Phaser.PluginManager(this, this);
  10574. this.net = new Phaser.Net(this);
  10575. this.debug = new Phaser.Utils.Debug(this);
  10576. this.stage.boot();
  10577. this.world.boot();
  10578. this.input.boot();
  10579. this.sound.boot();
  10580. this.state.boot();
  10581. this.load.onLoadComplete.add(this.loadComplete, this);
  10582. this.showDebugHeader();
  10583. this.isRunning = true;
  10584. this._loadComplete = false;
  10585. this.raf = new Phaser.RequestAnimationFrame(this);
  10586. this.raf.start();
  10587. }
  10588. },
  10589. /**
  10590. * Displays a Phaser version debug header in the console.
  10591. *
  10592. * @method Phaser.Game#showDebugHeader
  10593. * @protected
  10594. */
  10595. showDebugHeader: function () {
  10596. var v = Phaser.DEV_VERSION;
  10597. var r = 'Canvas';
  10598. var a = 'HTML Audio';
  10599. if (this.renderType == Phaser.WEBGL)
  10600. {
  10601. r = 'WebGL';
  10602. }
  10603. else if (this.renderType == Phaser.HEADLESS)
  10604. {
  10605. r = 'Headless';
  10606. }
  10607. if (this.device.webAudio)
  10608. {
  10609. a = 'WebAudio';
  10610. }
  10611. if (this.device.chrome)
  10612. {
  10613. var args = [
  10614. '%c %c %c Phaser v' + v + ' - Renderer: ' + r + ' - Audio: ' + a + ' %c %c ',
  10615. 'background: #00bff3',
  10616. 'background: #0072bc',
  10617. 'color: #ffffff; background: #003471',
  10618. 'background: #0072bc',
  10619. 'background: #00bff3'
  10620. ];
  10621. console.log.apply(console, args);
  10622. }
  10623. else
  10624. {
  10625. console.log('Phaser v' + v + ' - Renderer: ' + r + ' - Audio: ' + a);
  10626. }
  10627. },
  10628. /**
  10629. * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
  10630. *
  10631. * @method Phaser.Game#setUpRenderer
  10632. * @protected
  10633. */
  10634. setUpRenderer: function () {
  10635. if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && this.device.webGL === false))
  10636. {
  10637. if (this.device.canvas)
  10638. {
  10639. if (this.renderType === Phaser.AUTO)
  10640. {
  10641. this.renderType = Phaser.CANVAS;
  10642. }
  10643. this.renderer = new PIXI.CanvasRenderer(this.width, this.height, this.stage.canvas, this.transparent);
  10644. Phaser.Canvas.setSmoothingEnabled(this.renderer.context, this.antialias);
  10645. this.canvas = this.renderer.view;
  10646. this.context = this.renderer.context;
  10647. }
  10648. else
  10649. {
  10650. throw new Error('Phaser.Game - cannot create Canvas or WebGL context, aborting.');
  10651. }
  10652. }
  10653. else
  10654. {
  10655. // They requested WebGL, and their browser supports it
  10656. this.renderType = Phaser.WEBGL;
  10657. this.renderer = new PIXI.WebGLRenderer(this.width, this.height, this.stage.canvas, this.transparent, this.antialias);
  10658. this.canvas = this.renderer.view;
  10659. this.context = null;
  10660. }
  10661. Phaser.Canvas.addToDOM(this.renderer.view, this.parent, true);
  10662. Phaser.Canvas.setTouchAction(this.renderer.view);
  10663. },
  10664. /**
  10665. * Called when the load has finished, after preload was run.
  10666. *
  10667. * @method Phaser.Game#loadComplete
  10668. * @protected
  10669. */
  10670. loadComplete: function () {
  10671. this._loadComplete = true;
  10672. this.state.loadComplete();
  10673. },
  10674. /**
  10675. * The core game loop.
  10676. *
  10677. * @method Phaser.Game#update
  10678. * @protected
  10679. * @param {number} time - The current time as provided by RequestAnimationFrame.
  10680. */
  10681. update: function (time) {
  10682. this.time.update(time);
  10683. if (this._paused)
  10684. {
  10685. this.renderer.render(this.stage._stage);
  10686. this.plugins.render();
  10687. this.state.render();
  10688. this.world.postUpdate(); // qzix13
  10689. this.input.update(); // qzix13
  10690. }
  10691. else
  10692. {
  10693. this.plugins.preUpdate();
  10694. this.physics.preUpdate();
  10695. this.stage.update();
  10696. this.input.update();
  10697. this.tweens.update();
  10698. this.sound.update();
  10699. this.world.update();
  10700. this.particles.update();
  10701. this.state.update();
  10702. this.plugins.update();
  10703. this.world.postUpdate();
  10704. this.plugins.postUpdate();
  10705. if (this.renderType !== Phaser.HEADLESS)
  10706. {
  10707. this.renderer.render(this.stage._stage);
  10708. this.plugins.render();
  10709. this.state.render();
  10710. this.plugins.postRender();
  10711. }
  10712. }
  10713. },
  10714. /**
  10715. * Nuke the entire game from orbit
  10716. *
  10717. * @method Phaser.Game#destroy
  10718. */
  10719. destroy: function () {
  10720. this.raf.stop();
  10721. this.input.destroy();
  10722. this.state.destroy();
  10723. this.state = null;
  10724. this.cache = null;
  10725. this.input = null;
  10726. this.load = null;
  10727. this.sound = null;
  10728. this.stage = null;
  10729. this.time = null;
  10730. this.world = null;
  10731. this.isBooted = false;
  10732. }
  10733. };
  10734. /**
  10735. * The paused state of the Game. A paused game doesn't update any of its subsystems.
  10736. * When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
  10737. * @name Phaser.Game#paused
  10738. * @property {boolean} paused - Gets and sets the paused state of the Game.
  10739. */
  10740. Object.defineProperty(Phaser.Game.prototype, "paused", {
  10741. get: function () {
  10742. return this._paused;
  10743. },
  10744. set: function (value) {
  10745. //return;
  10746. if (value === true)
  10747. {
  10748. if (this._paused === false)
  10749. {
  10750. this._paused = true;
  10751. this.onPause.dispatch(this);
  10752. }
  10753. }
  10754. else
  10755. {
  10756. if (this._paused)
  10757. {
  10758. this._paused = false;
  10759. this.onResume.dispatch(this);
  10760. }
  10761. }
  10762. }
  10763. });
  10764. /**
  10765. * "Deleted code is debugged code." - Jeff Sickel
  10766. */
  10767. /**
  10768. * @author Richard Davey <rich@photonstorm.com>
  10769. * @copyright 2013 Photon Storm Ltd.
  10770. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  10771. */
  10772. /**
  10773. * Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer.
  10774. * The Input manager is updated automatically by the core game loop.
  10775. *
  10776. * @class Phaser.Input
  10777. * @constructor
  10778. * @param {Phaser.Game} game - Current game instance.
  10779. */
  10780. Phaser.Input = function (game) {
  10781. /**
  10782. * @property {Phaser.Game} game - A reference to the currently running game.
  10783. */
  10784. this.game = game;
  10785. /**
  10786. * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection.
  10787. * @default
  10788. */
  10789. this.hitCanvas = null;
  10790. /**
  10791. * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas.
  10792. * @default
  10793. */
  10794. this.hitContext = null;
  10795. };
  10796. /**
  10797. * @constant
  10798. * @type {number}
  10799. */
  10800. Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0;
  10801. /**
  10802. * @constant
  10803. * @type {number}
  10804. */
  10805. Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1;
  10806. /**
  10807. * @constant
  10808. * @type {number}
  10809. */
  10810. Phaser.Input.MOUSE_TOUCH_COMBINE = 2;
  10811. Phaser.Input.prototype = {
  10812. /**
  10813. * How often should the input pointers be checked for updates?
  10814. * A value of 0 means every single frame (60fps), a value of 1 means every other frame (30fps) and so on.
  10815. * @property {number} pollRate
  10816. * @default
  10817. */
  10818. pollRate: 0,
  10819. /**
  10820. * @property {number} _pollCounter - Internal var holding the current poll counter.
  10821. * @private
  10822. * @default
  10823. */
  10824. _pollCounter: 0,
  10825. /**
  10826. * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer.
  10827. * @private
  10828. * @default
  10829. */
  10830. _oldPosition: null,
  10831. /**
  10832. * @property {number} _x - x coordinate of the most recent Pointer event
  10833. * @private
  10834. * @default
  10835. */
  10836. _x: 0,
  10837. /**
  10838. * @property {number} _y - Y coordinate of the most recent Pointer event
  10839. * @private
  10840. * @default
  10841. */
  10842. _y: 0,
  10843. /**
  10844. * You can disable all Input by setting Input.disabled: true. While set all new input related events will be ignored.
  10845. * If you need to disable just one type of input, for example mouse, use Input.mouse.disabled: true instead
  10846. * @property {boolean} disabled
  10847. * @default
  10848. */
  10849. disabled: false,
  10850. /**
  10851. * Controls the expected behaviour when using a mouse and touch together on a multi-input device.
  10852. * @property {Description} multiInputOverride
  10853. */
  10854. multiInputOverride: Phaser.Input.MOUSE_TOUCH_COMBINE,
  10855. /**
  10856. * @property {Phaser.Point} position - A point object representing the current position of the Pointer.
  10857. * @default
  10858. */
  10859. position: null,
  10860. /**
  10861. * A point object representing the speed of the Pointer. Only really useful in single Pointer games, otherwise see the Pointer objects directly.
  10862. * @property {Phaser.Point} speed
  10863. */
  10864. speed: null,
  10865. /**
  10866. * A Circle object centered on the x/y screen coordinates of the Input.
  10867. * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything.
  10868. * @property {Phaser.Circle} circle
  10869. */
  10870. circle: null,
  10871. /**
  10872. * The scale by which all input coordinates are multiplied, calculated by the StageScaleMode.
  10873. * In an un-scaled game the values will be x: 1 and y: 1.
  10874. * @property {Phaser.Point} scale
  10875. */
  10876. scale: null,
  10877. /**
  10878. * The maximum number of Pointers allowed to be active at any one time.
  10879. * For lots of games it's useful to set this to 1.
  10880. * @property {number} maxPointers
  10881. * @default
  10882. */
  10883. maxPointers: 10,
  10884. /**
  10885. * The current number of active Pointers.
  10886. * @property {number} currentPointers
  10887. * @default
  10888. */
  10889. currentPointers: 0,
  10890. /**
  10891. * The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or clicke
  10892. * @property {number} tapRate
  10893. * @default
  10894. */
  10895. tapRate: 200,
  10896. /**
  10897. * The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click
  10898. * @property {number} doubleTapRate
  10899. * @default
  10900. */
  10901. doubleTapRate: 300,
  10902. /**
  10903. * The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event
  10904. * @property {number} holdRate
  10905. * @default
  10906. */
  10907. holdRate: 2000,
  10908. /**
  10909. * The number of milliseconds below which the Pointer is considered justPressed
  10910. * @property {number} justPressedRate
  10911. * @default
  10912. */
  10913. justPressedRate: 200,
  10914. /**
  10915. * The number of milliseconds below which the Pointer is considered justReleased
  10916. * @property {number} justReleasedRate
  10917. * @default
  10918. */
  10919. justReleasedRate: 200,
  10920. /**
  10921. * Sets if the Pointer objects should record a history of x/y coordinates they have passed through.
  10922. * The history is cleared each time the Pointer is pressed down.
  10923. * The history is updated at the rate specified in Input.pollRate
  10924. * @property {boolean} recordPointerHistory
  10925. * @default
  10926. */
  10927. recordPointerHistory: false,
  10928. /**
  10929. * The rate in milliseconds at which the Pointer objects should update their tracking history
  10930. * @property {number} recordRate
  10931. * @default
  10932. */
  10933. recordRate: 100,
  10934. /**
  10935. * The total number of entries that can be recorded into the Pointer objects tracking history.
  10936. * If the Pointer is tracking one event every 100ms, then a trackLimit of 100 would store the last 10 seconds worth of history.
  10937. * @property {number} recordLimit
  10938. * @default
  10939. */
  10940. recordLimit: 100,
  10941. /**
  10942. * A Pointer object
  10943. * @property {Phaser.Pointer} pointer1
  10944. */
  10945. pointer1: null,
  10946. /**
  10947. * A Pointer object
  10948. * @property {Phaser.Pointer} pointer2
  10949. */
  10950. pointer2: null,
  10951. /**
  10952. * A Pointer object
  10953. * @property {Phaser.Pointer} pointer3
  10954. */
  10955. pointer3: null,
  10956. /**
  10957. * A Pointer object
  10958. * @property {Phaser.Pointer} pointer4
  10959. */
  10960. pointer4: null,
  10961. /**
  10962. * A Pointer object
  10963. * @property {Phaser.Pointer} pointer5
  10964. */
  10965. pointer5: null,
  10966. /**
  10967. * A Pointer object
  10968. * @property {Phaser.Pointer} pointer6
  10969. */
  10970. pointer6: null,
  10971. /**
  10972. * A Pointer object
  10973. * @property {Phaser.Pointer} pointer7
  10974. */
  10975. pointer7: null,
  10976. /**
  10977. * A Pointer object
  10978. * @property {Phaser.Pointer} pointer8
  10979. */
  10980. pointer8: null,
  10981. /**
  10982. * A Pointer object
  10983. * @property {Phaser.Pointer} pointer9
  10984. */
  10985. pointer9: null,
  10986. /**
  10987. * A Pointer object.
  10988. * @property {Phaser.Pointer} pointer10
  10989. */
  10990. pointer10: null,
  10991. /**
  10992. * The most recently active Pointer object.
  10993. * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse.
  10994. * @property {Phaser.Pointer} activePointer
  10995. * @default
  10996. */
  10997. activePointer: null,
  10998. /**
  10999. * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game.
  11000. * @property {Pointer} mousePointer
  11001. * @default
  11002. */
  11003. mousePointer: null,
  11004. /**
  11005. * The Mouse Input manager.
  11006. * @property {Phaser.Mouse} mouse - The Mouse Input manager.
  11007. * @default
  11008. */
  11009. mouse: null,
  11010. /**
  11011. * The Keyboard Input manager.
  11012. * @property {Phaser.Keyboard} keyboard - The Keyboard Input manager.
  11013. * @default
  11014. */
  11015. keyboard: null,
  11016. /**
  11017. * The Touch Input manager.
  11018. * @property {Phaser.Touch} touch - the Touch Input manager.
  11019. * @default
  11020. */
  11021. touch: null,
  11022. /**
  11023. * The MSPointer Input manager.
  11024. * @property {Phaser.MSPointer} mspointer - The MSPointer Input manager.
  11025. * @default
  11026. */
  11027. mspointer: null,
  11028. /**
  11029. * A Signal that is dispatched each time a pointer is pressed down.
  11030. * @property {Phaser.Signal} onDown
  11031. * @default
  11032. */
  11033. onDown: null,
  11034. /**
  11035. * A Signal that is dispatched each time a pointer is released.
  11036. * @property {Phaser.Signal} onUp
  11037. * @default
  11038. */
  11039. onUp: null,
  11040. /**
  11041. * A Signal that is dispatched each time a pointer is tapped.
  11042. * @property {Phaser.Signal} onTap
  11043. * @default
  11044. */
  11045. onTap: null,
  11046. /**
  11047. * A Signal that is dispatched each time a pointer is held down.
  11048. * @property {Phaser.Signal} onHold
  11049. * @default
  11050. */
  11051. onHold: null,
  11052. /**
  11053. * A linked list of interactive objects, the InputHandler components (belonging to Sprites) register themselves with this.
  11054. * @property {Phaser.LinkedList} interactiveItems
  11055. */
  11056. interactiveItems: new Phaser.LinkedList(),
  11057. /**
  11058. * Starts the Input Manager running.
  11059. * @method Phaser.Input#boot
  11060. * @protected
  11061. */
  11062. boot: function () {
  11063. this.mousePointer = new Phaser.Pointer(this.game, 0);
  11064. this.pointer1 = new Phaser.Pointer(this.game, 1);
  11065. this.pointer2 = new Phaser.Pointer(this.game, 2);
  11066. this.mouse = new Phaser.Mouse(this.game);
  11067. this.keyboard = new Phaser.Keyboard(this.game);
  11068. this.touch = new Phaser.Touch(this.game);
  11069. this.mspointer = new Phaser.MSPointer(this.game);
  11070. this.onDown = new Phaser.Signal();
  11071. this.onUp = new Phaser.Signal();
  11072. this.onTap = new Phaser.Signal();
  11073. this.onHold = new Phaser.Signal();
  11074. this.scale = new Phaser.Point(1, 1);
  11075. this.speed = new Phaser.Point();
  11076. this.position = new Phaser.Point();
  11077. this._oldPosition = new Phaser.Point();
  11078. this.circle = new Phaser.Circle(0, 0, 44);
  11079. this.activePointer = this.mousePointer;
  11080. this.currentPointers = 0;
  11081. this.hitCanvas = document.createElement('canvas');
  11082. this.hitCanvas.width = 1;
  11083. this.hitCanvas.height = 1;
  11084. this.hitContext = this.hitCanvas.getContext('2d');
  11085. this.mouse.start();
  11086. this.keyboard.start();
  11087. this.touch.start();
  11088. this.mspointer.start();
  11089. this.mousePointer.active = true;
  11090. },
  11091. /**
  11092. * Stops all of the Input Managers from running.
  11093. * @method Phaser.Input#destroy
  11094. */
  11095. destroy: function () {
  11096. this.mouse.stop();
  11097. this.keyboard.stop();
  11098. this.touch.stop();
  11099. this.mspointer.stop();
  11100. },
  11101. /**
  11102. * Add a new Pointer object to the Input Manager. By default Input creates 3 pointer objects: mousePointer, pointer1 and pointer2.
  11103. * If you need more then use this to create a new one, up to a maximum of 10.
  11104. * @method Phaser.Input#addPointer
  11105. * @return {Phaser.Pointer} A reference to the new Pointer object that was created.
  11106. */
  11107. addPointer: function () {
  11108. var next = 0;
  11109. for (var i = 10; i > 0; i--)
  11110. {
  11111. if (this['pointer' + i] === null)
  11112. {
  11113. next = i;
  11114. }
  11115. }
  11116. if (next === 0)
  11117. {
  11118. console.warn("You can only have 10 Pointer objects");
  11119. return null;
  11120. }
  11121. else
  11122. {
  11123. this['pointer' + next] = new Phaser.Pointer(this.game, next);
  11124. return this['pointer' + next];
  11125. }
  11126. },
  11127. /**
  11128. * Updates the Input Manager. Called by the core Game loop.
  11129. * @method Phaser.Input#update
  11130. * @protected
  11131. */
  11132. update: function () {
  11133. if (this.pollRate > 0 && this._pollCounter < this.pollRate)
  11134. {
  11135. this._pollCounter++;
  11136. return;
  11137. }
  11138. this.speed.x = this.position.x - this._oldPosition.x;
  11139. this.speed.y = this.position.y - this._oldPosition.y;
  11140. this._oldPosition.copyFrom(this.position);
  11141. this.mousePointer.update();
  11142. this.pointer1.update();
  11143. this.pointer2.update();
  11144. if (this.pointer3) { this.pointer3.update(); }
  11145. if (this.pointer4) { this.pointer4.update(); }
  11146. if (this.pointer5) { this.pointer5.update(); }
  11147. if (this.pointer6) { this.pointer6.update(); }
  11148. if (this.pointer7) { this.pointer7.update(); }
  11149. if (this.pointer8) { this.pointer8.update(); }
  11150. if (this.pointer9) { this.pointer9.update(); }
  11151. if (this.pointer10) { this.pointer10.update(); }
  11152. this._pollCounter = 0;
  11153. },
  11154. /**
  11155. * Reset all of the Pointers and Input states
  11156. * @method Phaser.Input#reset
  11157. * @param {boolean} hard - A soft reset (hard = false) won't reset any Signals that might be bound. A hard reset will.
  11158. */
  11159. reset: function (hard) {
  11160. if (this.game.isBooted === false)
  11161. {
  11162. return;
  11163. }
  11164. if (typeof hard == 'undefined') { hard = false; }
  11165. this.keyboard.reset();
  11166. this.mousePointer.reset();
  11167. for (var i = 1; i <= 10; i++)
  11168. {
  11169. if (this['pointer' + i])
  11170. {
  11171. this['pointer' + i].reset();
  11172. }
  11173. }
  11174. this.currentPointers = 0;
  11175. this.game.stage.canvas.style.cursor = "default";
  11176. if (hard === true)
  11177. {
  11178. this.onDown.dispose();
  11179. this.onUp.dispose();
  11180. this.onTap.dispose();
  11181. this.onHold.dispose();
  11182. this.onDown = new Phaser.Signal();
  11183. this.onUp = new Phaser.Signal();
  11184. this.onTap = new Phaser.Signal();
  11185. this.onHold = new Phaser.Signal();
  11186. this.interactiveItems.callAll('reset');
  11187. }
  11188. this._pollCounter = 0;
  11189. },
  11190. /**
  11191. * Resets the speed and old position properties.
  11192. * @method Phaser.Input#resetSpeed
  11193. * @param {number} x - Sets the oldPosition.x value.
  11194. * @param {number} y - Sets the oldPosition.y value.
  11195. */
  11196. resetSpeed: function (x, y) {
  11197. this._oldPosition.setTo(x, y);
  11198. this.speed.setTo(0, 0);
  11199. },
  11200. /**
  11201. * Find the first free Pointer object and start it, passing in the event data. This is called automatically by Phaser.Touch and Phaser.MSPointer.
  11202. * @method Phaser.Input#startPointer
  11203. * @param {Any} event - The event data from the Touch event.
  11204. * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available.
  11205. */
  11206. startPointer: function (event) {
  11207. if (this.maxPointers < 10 && this.totalActivePointers == this.maxPointers)
  11208. {
  11209. return null;
  11210. }
  11211. if (this.pointer1.active === false)
  11212. {
  11213. return this.pointer1.start(event);
  11214. }
  11215. else if (this.pointer2.active === false)
  11216. {
  11217. return this.pointer2.start(event);
  11218. }
  11219. else
  11220. {
  11221. for (var i = 3; i <= 10; i++)
  11222. {
  11223. if (this['pointer' + i] && this['pointer' + i].active === false)
  11224. {
  11225. return this['pointer' + i].start(event);
  11226. }
  11227. }
  11228. }
  11229. return null;
  11230. },
  11231. /**
  11232. * Updates the matching Pointer object, passing in the event data. This is called automatically and should not normally need to be invoked.
  11233. * @method Phaser.Input#updatePointer
  11234. * @param {Any} event - The event data from the Touch event.
  11235. * @return {Phaser.Pointer} The Pointer object that was updated or null if no Pointer object is available.
  11236. */
  11237. updatePointer: function (event) {
  11238. if (this.pointer1.active && this.pointer1.identifier == event.identifier)
  11239. {
  11240. return this.pointer1.move(event);
  11241. }
  11242. else if (this.pointer2.active && this.pointer2.identifier == event.identifier)
  11243. {
  11244. return this.pointer2.move(event);
  11245. }
  11246. else
  11247. {
  11248. for (var i = 3; i <= 10; i++)
  11249. {
  11250. if (this['pointer' + i] && this['pointer' + i].active && this['pointer' + i].identifier == event.identifier)
  11251. {
  11252. return this['pointer' + i].move(event);
  11253. }
  11254. }
  11255. }
  11256. return null;
  11257. },
  11258. /**
  11259. * Stops the matching Pointer object, passing in the event data.
  11260. * @method Phaser.Input#stopPointer
  11261. * @param {Any} event - The event data from the Touch event.
  11262. * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available.
  11263. */
  11264. stopPointer: function (event) {
  11265. if (this.pointer1.active && this.pointer1.identifier == event.identifier)
  11266. {
  11267. return this.pointer1.stop(event);
  11268. }
  11269. else if (this.pointer2.active && this.pointer2.identifier == event.identifier)
  11270. {
  11271. return this.pointer2.stop(event);
  11272. }
  11273. else
  11274. {
  11275. for (var i = 3; i <= 10; i++)
  11276. {
  11277. if (this['pointer' + i] && this['pointer' + i].active && this['pointer' + i].identifier == event.identifier)
  11278. {
  11279. return this['pointer' + i].stop(event);
  11280. }
  11281. }
  11282. }
  11283. return null;
  11284. },
  11285. /**
  11286. * Get the next Pointer object whos active property matches the given state
  11287. * @method Phaser.Input#getPointer
  11288. * @param {boolean} state - The state the Pointer should be in (false for inactive, true for active).
  11289. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state.
  11290. */
  11291. getPointer: function (state) {
  11292. state = state || false;
  11293. if (this.pointer1.active == state)
  11294. {
  11295. return this.pointer1;
  11296. }
  11297. else if (this.pointer2.active == state)
  11298. {
  11299. return this.pointer2;
  11300. }
  11301. else
  11302. {
  11303. for (var i = 3; i <= 10; i++)
  11304. {
  11305. if (this['pointer' + i] && this['pointer' + i].active == state)
  11306. {
  11307. return this['pointer' + i];
  11308. }
  11309. }
  11310. }
  11311. return null;
  11312. },
  11313. /**
  11314. * Get the Pointer object whos identified property matches the given identifier value.
  11315. * @method Phaser.Input#getPointerFromIdentifier
  11316. * @param {number} identifier - The Pointer.identifier value to search for.
  11317. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
  11318. */
  11319. getPointerFromIdentifier: function (identifier) {
  11320. if (this.pointer1.identifier == identifier)
  11321. {
  11322. return this.pointer1;
  11323. }
  11324. else if (this.pointer2.identifier == identifier)
  11325. {
  11326. return this.pointer2;
  11327. }
  11328. else
  11329. {
  11330. for (var i = 3; i <= 10; i++)
  11331. {
  11332. if (this['pointer' + i] && this['pointer' + i].identifier == identifier)
  11333. {
  11334. return this['pointer' + i];
  11335. }
  11336. }
  11337. }
  11338. return null;
  11339. }
  11340. };
  11341. /**
  11342. * The X coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values.
  11343. * @name Phaser.Input#x
  11344. * @property {number} x - The X coordinate of the most recently active pointer.
  11345. */
  11346. Object.defineProperty(Phaser.Input.prototype, "x", {
  11347. get: function () {
  11348. return this._x;
  11349. },
  11350. set: function (value) {
  11351. this._x = Math.floor(value);
  11352. }
  11353. });
  11354. /**
  11355. * The Y coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values.
  11356. * @name Phaser.Input#y
  11357. * @property {number} y - The Y coordinate of the most recently active pointer.
  11358. */
  11359. Object.defineProperty(Phaser.Input.prototype, "y", {
  11360. get: function () {
  11361. return this._y;
  11362. },
  11363. set: function (value) {
  11364. this._y = Math.floor(value);
  11365. }
  11366. });
  11367. /**
  11368. * @name Phaser.Input#pollLocked
  11369. * @property {boolean} pollLocked - True if the Input is currently poll rate locked.
  11370. * @readonly
  11371. */
  11372. Object.defineProperty(Phaser.Input.prototype, "pollLocked", {
  11373. get: function () {
  11374. return (this.pollRate > 0 && this._pollCounter < this.pollRate);
  11375. }
  11376. });
  11377. /**
  11378. * The total number of inactive Pointers
  11379. * @name Phaser.Input#totalInactivePointers
  11380. * @property {number} totalInactivePointers - The total number of inactive Pointers.
  11381. * @readonly
  11382. */
  11383. Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", {
  11384. get: function () {
  11385. return 10 - this.currentPointers;
  11386. }
  11387. });
  11388. /**
  11389. * The total number of active Pointers
  11390. * @name Phaser.Input#totalActivePointers
  11391. * @property {number} totalActivePointers - The total number of active Pointers.
  11392. * @readonly
  11393. */
  11394. Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", {
  11395. get: function () {
  11396. this.currentPointers = 0;
  11397. for (var i = 1; i <= 10; i++)
  11398. {
  11399. if (this['pointer' + i] && this['pointer' + i].active)
  11400. {
  11401. this.currentPointers++;
  11402. }
  11403. }
  11404. return this.currentPointers;
  11405. }
  11406. });
  11407. /**
  11408. * The world X coordinate of the most recently active pointer.
  11409. * @name Phaser.Input#worldX
  11410. * @property {number} worldX - The world X coordinate of the most recently active pointer.
  11411. */
  11412. Object.defineProperty(Phaser.Input.prototype, "worldX", {
  11413. get: function () {
  11414. return this.game.camera.view.x + this.x;
  11415. }
  11416. });
  11417. /**
  11418. * The world Y coordinate of the most recently active pointer.
  11419. * @name Phaser.Input#worldY
  11420. * @property {number} worldY - The world Y coordinate of the most recently active pointer.
  11421. */
  11422. Object.defineProperty(Phaser.Input.prototype, "worldY", {
  11423. get: function () {
  11424. return this.game.camera.view.y + this.y;
  11425. }
  11426. });
  11427. /**
  11428. * @author Richard Davey <rich@photonstorm.com>
  11429. * @copyright 2013 Photon Storm Ltd.
  11430. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  11431. */
  11432. /**
  11433. * @class Phaser.Key
  11434. * @classdesc If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects.
  11435. * @constructor
  11436. * @param {Phaser.Game} game - Current game instance.
  11437. * @param {number} keycode - The key code this Key is responsible for.
  11438. */
  11439. Phaser.Key = function (game, keycode) {
  11440. /**
  11441. * @property {Phaser.Game} game - A reference to the currently running game.
  11442. */
  11443. this.game = game;
  11444. /**
  11445. * @property {boolean} isDown - The "down" state of the key.
  11446. * @default
  11447. */
  11448. this.isDown = false;
  11449. /**
  11450. * @property {boolean} isUp - The "up" state of the key.
  11451. * @default
  11452. */
  11453. this.isUp = false;
  11454. /**
  11455. * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key.
  11456. * @default
  11457. */
  11458. this.altKey = false;
  11459. /**
  11460. * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key.
  11461. * @default
  11462. */
  11463. this.ctrlKey = false;
  11464. /**
  11465. * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key.
  11466. * @default
  11467. */
  11468. this.shiftKey = false;
  11469. /**
  11470. * @property {number} timeDown - The timestamp when the key was last pressed down.
  11471. * @default
  11472. */
  11473. this.timeDown = 0;
  11474. /**
  11475. * If the key is down this value holds the duration of that key press and is constantly updated.
  11476. * If the key is up it holds the duration of the previous down session.
  11477. * @property {number} duration - The number of milliseconds this key has been held down for.
  11478. * @default
  11479. */
  11480. this.duration = 0;
  11481. /**
  11482. * @property {number} timeUp - The timestamp when the key was last released.
  11483. * @default
  11484. */
  11485. this.timeUp = 0;
  11486. /**
  11487. * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'.
  11488. * @default
  11489. */
  11490. this.repeats = 0;
  11491. /**
  11492. * @property {number} keyCode - The keycode of this key.
  11493. */
  11494. this.keyCode = keycode;
  11495. /**
  11496. * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
  11497. */
  11498. this.onDown = new Phaser.Signal();
  11499. /**
  11500. * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
  11501. */
  11502. this.onUp = new Phaser.Signal();
  11503. };
  11504. Phaser.Key.prototype = {
  11505. /**
  11506. * Called automatically by Phaser.Keyboard.
  11507. * @method Phaser.Key#processKeyDown
  11508. * @param {KeyboardEvent} event.
  11509. * @protected
  11510. */
  11511. processKeyDown: function (event) {
  11512. this.altKey = event.altKey;
  11513. this.ctrlKey = event.ctrlKey;
  11514. this.shiftKey = event.shiftKey;
  11515. if (this.isDown)
  11516. {
  11517. // Key was already held down, this must be a repeat rate based event
  11518. this.duration = event.timeStamp - this.timeDown;
  11519. this.repeats++;
  11520. }
  11521. else
  11522. {
  11523. this.isDown = true;
  11524. this.isUp = false;
  11525. this.timeDown = event.timeStamp;
  11526. this.duration = 0;
  11527. this.repeats = 0;
  11528. this.onDown.dispatch(this);
  11529. }
  11530. },
  11531. /**
  11532. * Called automatically by Phaser.Keyboard.
  11533. * @method Phaser.Key#processKeyUp
  11534. * @param {KeyboardEvent} event.
  11535. * @protected
  11536. */
  11537. processKeyUp: function (event) {
  11538. this.isDown = false;
  11539. this.isUp = true;
  11540. this.timeUp = event.timeStamp;
  11541. this.onUp.dispatch(this);
  11542. },
  11543. /**
  11544. * Returns the "just pressed" state of the Key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms)
  11545. * @method Phaser.Key#justPressed
  11546. * @param {number} [duration=250] - The duration below which the key is considered as being just pressed.
  11547. * @return {boolean} True if the key is just pressed otherwise false.
  11548. */
  11549. justPressed: function (duration) {
  11550. if (typeof duration === "undefined") { duration = 250; }
  11551. return (this.isDown && this.duration < duration);
  11552. },
  11553. /**
  11554. * Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms)
  11555. * @method Phaser.Key#justPressed
  11556. * @param {number} [duration=250] - The duration below which the key is considered as being just released.
  11557. * @return {boolean} True if the key is just released otherwise false.
  11558. */
  11559. justReleased: function (duration) {
  11560. if (typeof duration === "undefined") { duration = 250; }
  11561. return (this.isDown === false && (this.game.time.now - this.timeUp < duration));
  11562. }
  11563. };
  11564. /**
  11565. * @author Richard Davey <rich@photonstorm.com>
  11566. * @copyright 2013 Photon Storm Ltd.
  11567. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  11568. */
  11569. /**
  11570. * The Keyboard class handles looking after keyboard input for your game. It will recognise and respond to key presses and dispatch the required events.
  11571. *
  11572. * @class Phaser.Keyboard
  11573. * @constructor
  11574. * @param {Phaser.Game} game - A reference to the currently running game.
  11575. */
  11576. Phaser.Keyboard = function (game) {
  11577. /**
  11578. * @property {Phaser.Game} game - Local reference to game.
  11579. */
  11580. this.game = game;
  11581. /**
  11582. * @property {object} _keys - The object the key values are stored in.
  11583. * @private
  11584. */
  11585. this._keys = {};
  11586. /**
  11587. * @property {object} _hotkeys - The object the hot keys are stored in.
  11588. * @private
  11589. */
  11590. this._hotkeys = {};
  11591. /**
  11592. * @property {object} _capture - The object the key capture values are stored in.
  11593. * @private
  11594. */
  11595. this._capture = {};
  11596. /**
  11597. * You can disable all Keyboard Input by setting disabled to true. While true all new input related events will be ignored.
  11598. * @property {boolean} disabled - The disabled state of the Keyboard.
  11599. * @default
  11600. */
  11601. this.disabled = false;
  11602. /**
  11603. * @property {function} _onKeyDown
  11604. * @private
  11605. * @default
  11606. */
  11607. this._onKeyDown = null;
  11608. /**
  11609. * @property {function} _onKeyUp
  11610. * @private
  11611. * @default
  11612. */
  11613. this._onKeyUp = null;
  11614. /**
  11615. * @property {Object} callbackContext - The context under which the callbacks are run.
  11616. */
  11617. this.callbackContext = this;
  11618. /**
  11619. * @property {function} onDownCallback - This callback is invoked every time a key is pressed down.
  11620. */
  11621. this.onDownCallback = null;
  11622. /**
  11623. * @property {function} onUpCallback - This callback is invoked every time a key is released.
  11624. */
  11625. this.onUpCallback = null;
  11626. };
  11627. Phaser.Keyboard.prototype = {
  11628. /**
  11629. * Add callbacks to the Keyboard handler so that each time a key is pressed down or releases the callbacks are activated.
  11630. * @method Phaser.Keyboard#addCallbacks
  11631. * @param {Object} context - The context under which the callbacks are run.
  11632. * @param {function} onDown - This callback is invoked every time a key is pressed down.
  11633. * @param {function} [onUp=null] - This callback is invoked every time a key is released.
  11634. */
  11635. addCallbacks: function (context, onDown, onUp) {
  11636. this.callbackContext = context;
  11637. this.onDownCallback = onDown;
  11638. if (typeof onUp !== 'undefined')
  11639. {
  11640. this.onUpCallback = onUp;
  11641. }
  11642. },
  11643. /**
  11644. * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
  11645. * The Key object can then be polled, have events attached to it, etc.
  11646. *
  11647. * @method Phaser.Keyboard#addKey
  11648. * @param {number} keycode - The keycode of the key, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACE_BAR
  11649. * @return {Phaser.Key} The Key object which you can store locally and reference directly.
  11650. */
  11651. addKey: function (keycode) {
  11652. this._hotkeys[keycode] = new Phaser.Key(this.game, keycode);
  11653. this.addKeyCapture(keycode);
  11654. return this._hotkeys[keycode];
  11655. },
  11656. /**
  11657. * Removes a Key object from the Keyboard manager.
  11658. *
  11659. * @method Phaser.Keyboard#removeKey
  11660. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACE_BAR
  11661. */
  11662. removeKey: function (keycode) {
  11663. delete (this._hotkeys[keycode]);
  11664. },
  11665. /**
  11666. * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right.
  11667. *
  11668. * @method Phaser.Keyboard#createCursorKeys
  11669. * @return {object} An object containing properties: up, down, left and right. Which can be polled like any other Phaser.Key object.
  11670. */
  11671. createCursorKeys: function () {
  11672. return {
  11673. up: this.addKey(Phaser.Keyboard.UP),
  11674. down: this.addKey(Phaser.Keyboard.DOWN),
  11675. left: this.addKey(Phaser.Keyboard.LEFT),
  11676. right: this.addKey(Phaser.Keyboard.RIGHT)
  11677. }
  11678. },
  11679. /**
  11680. * Starts the Keyboard event listeners running (keydown and keyup). They are attached to the document.body.
  11681. * This is called automatically by Phaser.Input and should not normally be invoked directly.
  11682. *
  11683. * @method Phaser.Keyboard#start
  11684. */
  11685. start: function () {
  11686. var _this = this;
  11687. this._onKeyDown = function (event) {
  11688. return _this.processKeyDown(event);
  11689. };
  11690. this._onKeyUp = function (event) {
  11691. return _this.processKeyUp(event);
  11692. };
  11693. window.addEventListener('keydown', this._onKeyDown, false);
  11694. window.addEventListener('keyup', this._onKeyUp, false);
  11695. },
  11696. /**
  11697. * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the document.body.
  11698. *
  11699. * @method Phaser.Keyboard#stop
  11700. */
  11701. stop: function () {
  11702. window.removeEventListener('keydown', this._onKeyDown);
  11703. window.removeEventListener('keyup', this._onKeyUp);
  11704. },
  11705. /**
  11706. * By default when a key is pressed Phaser will not stop the event from propagating up to the browser.
  11707. * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll.
  11708. * You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser.
  11709. * Pass in either a single keycode or an array/hash of keycodes.
  11710. * @method Phaser.Keyboard#addKeyCapture
  11711. * @param {Any} keycode
  11712. */
  11713. addKeyCapture: function (keycode) {
  11714. if (typeof keycode === 'object')
  11715. {
  11716. for (var key in keycode)
  11717. {
  11718. this._capture[keycode[key]] = true;
  11719. }
  11720. }
  11721. else
  11722. {
  11723. this._capture[keycode] = true;
  11724. }
  11725. },
  11726. /**
  11727. * Removes an existing key capture.
  11728. * @method Phaser.Keyboard#removeKeyCapture
  11729. * @param {number} keycode
  11730. */
  11731. removeKeyCapture: function (keycode) {
  11732. delete this._capture[keycode];
  11733. },
  11734. /**
  11735. * Clear all set key captures.
  11736. * @method Phaser.Keyboard#clearCaptures
  11737. */
  11738. clearCaptures: function () {
  11739. this._capture = {};
  11740. },
  11741. /**
  11742. * Process the keydown event.
  11743. * @method Phaser.Keyboard#processKeyDown
  11744. * @param {KeyboardEvent} event
  11745. * @protected
  11746. */
  11747. processKeyDown: function (event) {
  11748. if (this.game.input.disabled || this.disabled)
  11749. {
  11750. return;
  11751. }
  11752. if (this._capture[event.keyCode])
  11753. {
  11754. event.preventDefault();
  11755. }
  11756. if (this.onDownCallback)
  11757. {
  11758. this.onDownCallback.call(this.callbackContext, event);
  11759. }
  11760. if (this._keys[event.keyCode] && this._keys[event.keyCode].isDown)
  11761. {
  11762. // Key already down and still down, so update
  11763. this._keys[event.keyCode].duration = this.game.time.now - this._keys[event.keyCode].timeDown;
  11764. }
  11765. else
  11766. {
  11767. if (!this._keys[event.keyCode])
  11768. {
  11769. // Not used this key before, so register it
  11770. this._keys[event.keyCode] = {
  11771. isDown: true,
  11772. timeDown: this.game.time.now,
  11773. timeUp: 0,
  11774. duration: 0
  11775. };
  11776. }
  11777. else
  11778. {
  11779. // Key used before but freshly down
  11780. this._keys[event.keyCode].isDown = true;
  11781. this._keys[event.keyCode].timeDown = this.game.time.now;
  11782. this._keys[event.keyCode].duration = 0;
  11783. }
  11784. }
  11785. if (this._hotkeys[event.keyCode])
  11786. {
  11787. this._hotkeys[event.keyCode].processKeyDown(event);
  11788. }
  11789. },
  11790. /**
  11791. * Process the keyup event.
  11792. * @method Phaser.Keyboard#processKeyUp
  11793. * @param {KeyboardEvent} event
  11794. * @protected
  11795. */
  11796. processKeyUp: function (event) {
  11797. if (this.game.input.disabled || this.disabled)
  11798. {
  11799. return;
  11800. }
  11801. if (this._capture[event.keyCode])
  11802. {
  11803. event.preventDefault();
  11804. }
  11805. if (this.onUpCallback)
  11806. {
  11807. this.onUpCallback.call(this.callbackContext, event);
  11808. }
  11809. if (this._hotkeys[event.keyCode])
  11810. {
  11811. this._hotkeys[event.keyCode].processKeyUp(event);
  11812. }
  11813. if (this._keys[event.keyCode])
  11814. {
  11815. this._keys[event.keyCode].isDown = false;
  11816. this._keys[event.keyCode].timeUp = this.game.time.now;
  11817. }
  11818. else
  11819. {
  11820. // Not used this key before, so register it
  11821. this._keys[event.keyCode] = {
  11822. isDown: false,
  11823. timeDown: this.game.time.now,
  11824. timeUp: this.game.time.now,
  11825. duration: 0
  11826. };
  11827. }
  11828. },
  11829. /**
  11830. * Reset the "isDown" state of all keys.
  11831. * @method Phaser.Keyboard#reset
  11832. */
  11833. reset: function () {
  11834. for (var key in this._keys)
  11835. {
  11836. this._keys[key].isDown = false;
  11837. }
  11838. },
  11839. /**
  11840. * Returns the "just pressed" state of the key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms)
  11841. * @method Phaser.Keyboard#justPressed
  11842. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACE_BAR
  11843. * @param {number} [duration=250] - The duration below which the key is considered as being just pressed.
  11844. * @return {boolean} True if the key is just pressed otherwise false.
  11845. */
  11846. justPressed: function (keycode, duration) {
  11847. if (typeof duration === "undefined") { duration = 250; }
  11848. if (this._keys[keycode] && this._keys[keycode].isDown && this._keys[keycode].duration < duration)
  11849. {
  11850. return true;
  11851. }
  11852. return false;
  11853. },
  11854. /**
  11855. * Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms)
  11856. * @method Phaser.Keyboard#justPressed
  11857. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACE_BAR
  11858. * @param {number} [duration=250] - The duration below which the key is considered as being just released.
  11859. * @return {boolean} True if the key is just released otherwise false.
  11860. */
  11861. justReleased: function (keycode, duration) {
  11862. if (typeof duration === "undefined") { duration = 250; }
  11863. if (this._keys[keycode] && this._keys[keycode].isDown === false && (this.game.time.now - this._keys[keycode].timeUp < duration))
  11864. {
  11865. return true;
  11866. }
  11867. return false;
  11868. },
  11869. /**
  11870. * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser.
  11871. * @method Phaser.Keyboard#isDown
  11872. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACE_BAR
  11873. * @return {boolean} True if the key is currently down.
  11874. */
  11875. isDown: function (keycode) {
  11876. if (this._keys[keycode])
  11877. {
  11878. return this._keys[keycode].isDown;
  11879. }
  11880. return false;
  11881. }
  11882. };
  11883. Phaser.Keyboard.A = "A".charCodeAt(0);
  11884. Phaser.Keyboard.B = "B".charCodeAt(0);
  11885. Phaser.Keyboard.C = "C".charCodeAt(0);
  11886. Phaser.Keyboard.D = "D".charCodeAt(0);
  11887. Phaser.Keyboard.E = "E".charCodeAt(0);
  11888. Phaser.Keyboard.F = "F".charCodeAt(0);
  11889. Phaser.Keyboard.G = "G".charCodeAt(0);
  11890. Phaser.Keyboard.H = "H".charCodeAt(0);
  11891. Phaser.Keyboard.I = "I".charCodeAt(0);
  11892. Phaser.Keyboard.J = "J".charCodeAt(0);
  11893. Phaser.Keyboard.K = "K".charCodeAt(0);
  11894. Phaser.Keyboard.L = "L".charCodeAt(0);
  11895. Phaser.Keyboard.M = "M".charCodeAt(0);
  11896. Phaser.Keyboard.N = "N".charCodeAt(0);
  11897. Phaser.Keyboard.O = "O".charCodeAt(0);
  11898. Phaser.Keyboard.P = "P".charCodeAt(0);
  11899. Phaser.Keyboard.Q = "Q".charCodeAt(0);
  11900. Phaser.Keyboard.R = "R".charCodeAt(0);
  11901. Phaser.Keyboard.S = "S".charCodeAt(0);
  11902. Phaser.Keyboard.T = "T".charCodeAt(0);
  11903. Phaser.Keyboard.U = "U".charCodeAt(0);
  11904. Phaser.Keyboard.V = "V".charCodeAt(0);
  11905. Phaser.Keyboard.W = "W".charCodeAt(0);
  11906. Phaser.Keyboard.X = "X".charCodeAt(0);
  11907. Phaser.Keyboard.Y = "Y".charCodeAt(0);
  11908. Phaser.Keyboard.Z = "Z".charCodeAt(0);
  11909. Phaser.Keyboard.ZERO = "0".charCodeAt(0);
  11910. Phaser.Keyboard.ONE = "1".charCodeAt(0);
  11911. Phaser.Keyboard.TWO = "2".charCodeAt(0);
  11912. Phaser.Keyboard.THREE = "3".charCodeAt(0);
  11913. Phaser.Keyboard.FOUR = "4".charCodeAt(0);
  11914. Phaser.Keyboard.FIVE = "5".charCodeAt(0);
  11915. Phaser.Keyboard.SIX = "6".charCodeAt(0);
  11916. Phaser.Keyboard.SEVEN = "7".charCodeAt(0);
  11917. Phaser.Keyboard.EIGHT = "8".charCodeAt(0);
  11918. Phaser.Keyboard.NINE = "9".charCodeAt(0);
  11919. Phaser.Keyboard.NUMPAD_0 = 96;
  11920. Phaser.Keyboard.NUMPAD_1 = 97;
  11921. Phaser.Keyboard.NUMPAD_2 = 98;
  11922. Phaser.Keyboard.NUMPAD_3 = 99;
  11923. Phaser.Keyboard.NUMPAD_4 = 100;
  11924. Phaser.Keyboard.NUMPAD_5 = 101;
  11925. Phaser.Keyboard.NUMPAD_6 = 102;
  11926. Phaser.Keyboard.NUMPAD_7 = 103;
  11927. Phaser.Keyboard.NUMPAD_8 = 104;
  11928. Phaser.Keyboard.NUMPAD_9 = 105;
  11929. Phaser.Keyboard.NUMPAD_MULTIPLY = 106;
  11930. Phaser.Keyboard.NUMPAD_ADD = 107;
  11931. Phaser.Keyboard.NUMPAD_ENTER = 108;
  11932. Phaser.Keyboard.NUMPAD_SUBTRACT = 109;
  11933. Phaser.Keyboard.NUMPAD_DECIMAL = 110;
  11934. Phaser.Keyboard.NUMPAD_DIVIDE = 111;
  11935. Phaser.Keyboard.F1 = 112;
  11936. Phaser.Keyboard.F2 = 113;
  11937. Phaser.Keyboard.F3 = 114;
  11938. Phaser.Keyboard.F4 = 115;
  11939. Phaser.Keyboard.F5 = 116;
  11940. Phaser.Keyboard.F6 = 117;
  11941. Phaser.Keyboard.F7 = 118;
  11942. Phaser.Keyboard.F8 = 119;
  11943. Phaser.Keyboard.F9 = 120;
  11944. Phaser.Keyboard.F10 = 121;
  11945. Phaser.Keyboard.F11 = 122;
  11946. Phaser.Keyboard.F12 = 123;
  11947. Phaser.Keyboard.F13 = 124;
  11948. Phaser.Keyboard.F14 = 125;
  11949. Phaser.Keyboard.F15 = 126;
  11950. Phaser.Keyboard.COLON = 186;
  11951. Phaser.Keyboard.EQUALS = 187;
  11952. Phaser.Keyboard.UNDERSCORE = 189;
  11953. Phaser.Keyboard.QUESTION_MARK = 191;
  11954. Phaser.Keyboard.TILDE = 192;
  11955. Phaser.Keyboard.OPEN_BRACKET = 219;
  11956. Phaser.Keyboard.BACKWARD_SLASH = 220;
  11957. Phaser.Keyboard.CLOSED_BRACKET = 221;
  11958. Phaser.Keyboard.QUOTES = 222;
  11959. Phaser.Keyboard.BACKSPACE = 8;
  11960. Phaser.Keyboard.TAB = 9;
  11961. Phaser.Keyboard.CLEAR = 12;
  11962. Phaser.Keyboard.ENTER = 13;
  11963. Phaser.Keyboard.SHIFT = 16;
  11964. Phaser.Keyboard.CONTROL = 17;
  11965. Phaser.Keyboard.ALT = 18;
  11966. Phaser.Keyboard.CAPS_LOCK = 20;
  11967. Phaser.Keyboard.ESC = 27;
  11968. Phaser.Keyboard.SPACEBAR = 32;
  11969. Phaser.Keyboard.PAGE_UP = 33;
  11970. Phaser.Keyboard.PAGE_DOWN = 34;
  11971. Phaser.Keyboard.END = 35;
  11972. Phaser.Keyboard.HOME = 36;
  11973. Phaser.Keyboard.LEFT = 37;
  11974. Phaser.Keyboard.UP = 38;
  11975. Phaser.Keyboard.RIGHT = 39;
  11976. Phaser.Keyboard.DOWN = 40;
  11977. Phaser.Keyboard.INSERT = 45;
  11978. Phaser.Keyboard.DELETE = 46;
  11979. Phaser.Keyboard.HELP = 47;
  11980. Phaser.Keyboard.NUM_LOCK = 144;
  11981. /**
  11982. * @author Richard Davey <rich@photonstorm.com>
  11983. * @copyright 2013 Photon Storm Ltd.
  11984. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  11985. */
  11986. /**
  11987. * Phaser.Mouse is responsible for handling all aspects of mouse interaction with the browser. It captures and processes mouse events.
  11988. *
  11989. * @class Phaser.Mouse
  11990. * @constructor
  11991. * @param {Phaser.Game} game - A reference to the currently running game.
  11992. */
  11993. Phaser.Mouse = function (game) {
  11994. /**
  11995. * @property {Phaser.Game} game - A reference to the currently running game.
  11996. */
  11997. this.game = game;
  11998. /**
  11999. * @property {Object} callbackContext - The context under which callbacks are called.
  12000. */
  12001. this.callbackContext = this.game;
  12002. /**
  12003. * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down.
  12004. */
  12005. this.mouseDownCallback = null;
  12006. /**
  12007. * @property {function} mouseMoveCallback - A callback that can be fired when the mouse is moved while pressed down.
  12008. */
  12009. this.mouseMoveCallback = null;
  12010. /**
  12011. * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state.
  12012. */
  12013. this.mouseUpCallback = null;
  12014. /**
  12015. * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propogate fully.
  12016. */
  12017. this.capture = false;
  12018. /**
  12019. * @property {number} button- The type of click, either: Phaser.Mouse.NO_BUTTON, Phaser.Mouse.LEFT_BUTTON, Phaser.Mouse.MIDDLE_BUTTON or Phaser.Mouse.RIGHT_BUTTON.
  12020. * @default
  12021. */
  12022. this.button = -1;
  12023. /**
  12024. * @property {boolean} disabled - You can disable all Input by setting disabled = true. While set all new input related events will be ignored.
  12025. * @default
  12026. */
  12027. this.disabled = false;
  12028. /**
  12029. * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true.
  12030. * @default
  12031. */
  12032. this.locked = false;
  12033. /**
  12034. * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state.
  12035. * @default
  12036. */
  12037. this.pointerLock = new Phaser.Signal();
  12038. /**
  12039. * @property {MouseEvent} event - The browser mouse event.
  12040. */
  12041. this.event = null;
  12042. /**
  12043. * @property {function} _onMouseDown - Internal event handler reference.
  12044. * @private
  12045. */
  12046. this._onMouseDown = null;
  12047. /**
  12048. * @property {function} _onMouseMove - Internal event handler reference.
  12049. * @private
  12050. */
  12051. this._onMouseMove = null;
  12052. /**
  12053. * @property {function} _onMouseUp - Internal event handler reference.
  12054. * @private
  12055. */
  12056. this._onMouseUp = null;
  12057. };
  12058. /**
  12059. * @constant
  12060. * @type {number}
  12061. */
  12062. Phaser.Mouse.NO_BUTTON = -1;
  12063. /**
  12064. * @constant
  12065. * @type {number}
  12066. */
  12067. Phaser.Mouse.LEFT_BUTTON = 0;
  12068. /**
  12069. * @constant
  12070. * @type {number}
  12071. */
  12072. Phaser.Mouse.MIDDLE_BUTTON = 1;
  12073. /**
  12074. * @constant
  12075. * @type {number}
  12076. */
  12077. Phaser.Mouse.RIGHT_BUTTON = 2;
  12078. Phaser.Mouse.prototype = {
  12079. /**
  12080. * Starts the event listeners running.
  12081. * @method Phaser.Mouse#start
  12082. */
  12083. start: function () {
  12084. var _this = this;
  12085. if (this.game.device.android && this.game.device.chrome === false)
  12086. {
  12087. // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ...
  12088. return;
  12089. }
  12090. this._onMouseDown = function (event) {
  12091. return _this.onMouseDown(event);
  12092. };
  12093. this._onMouseMove = function (event) {
  12094. return _this.onMouseMove(event);
  12095. };
  12096. this._onMouseUp = function (event) {
  12097. return _this.onMouseUp(event);
  12098. };
  12099. document.addEventListener('mousedown', this._onMouseDown, true);
  12100. document.addEventListener('mousemove', this._onMouseMove, true);
  12101. document.addEventListener('mouseup', this._onMouseUp, true);
  12102. },
  12103. /**
  12104. * The internal method that handles the mouse down event from the browser.
  12105. * @method Phaser.Mouse#onMouseDown
  12106. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  12107. */
  12108. onMouseDown: function (event) {
  12109. this.event = event;
  12110. if (this.capture)
  12111. {
  12112. event.preventDefault();
  12113. }
  12114. this.button = event.which;
  12115. if (this.mouseDownCallback)
  12116. {
  12117. this.mouseDownCallback.call(this.callbackContext, event);
  12118. }
  12119. if (this.game.input.disabled || this.disabled)
  12120. {
  12121. return;
  12122. }
  12123. event['identifier'] = 0;
  12124. this.game.input.mousePointer.start(event);
  12125. },
  12126. /**
  12127. * The internal method that handles the mouse move event from the browser.
  12128. * @method Phaser.Mouse#onMouseMove
  12129. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  12130. */
  12131. onMouseMove: function (event) {
  12132. this.event = event;
  12133. if (this.capture)
  12134. {
  12135. event.preventDefault();
  12136. }
  12137. if (this.mouseMoveCallback)
  12138. {
  12139. this.mouseMoveCallback.call(this.callbackContext, event);
  12140. }
  12141. if (this.game.input.disabled || this.disabled)
  12142. {
  12143. return;
  12144. }
  12145. event['identifier'] = 0;
  12146. this.game.input.mousePointer.move(event);
  12147. },
  12148. /**
  12149. * The internal method that handles the mouse up event from the browser.
  12150. * @method Phaser.Mouse#onMouseUp
  12151. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  12152. */
  12153. onMouseUp: function (event) {
  12154. this.event = event;
  12155. if (this.capture)
  12156. {
  12157. event.preventDefault();
  12158. }
  12159. this.button = Phaser.Mouse.NO_BUTTON;
  12160. if (this.mouseUpCallback)
  12161. {
  12162. this.mouseUpCallback.call(this.callbackContext, event);
  12163. }
  12164. if (this.game.input.disabled || this.disabled)
  12165. {
  12166. return;
  12167. }
  12168. event['identifier'] = 0;
  12169. this.game.input.mousePointer.stop(event);
  12170. },
  12171. /**
  12172. * If the browser supports it you can request that the pointer be locked to the browser window.
  12173. * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key.
  12174. * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'.
  12175. * @method Phaser.Mouse#requestPointerLock
  12176. */
  12177. requestPointerLock: function () {
  12178. if (this.game.device.pointerLock)
  12179. {
  12180. var element = this.game.stage.canvas;
  12181. element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
  12182. element.requestPointerLock();
  12183. var _this = this;
  12184. this._pointerLockChange = function (event) {
  12185. return _this.pointerLockChange(event);
  12186. };
  12187. document.addEventListener('pointerlockchange', this._pointerLockChange, true);
  12188. document.addEventListener('mozpointerlockchange', this._pointerLockChange, true);
  12189. document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  12190. }
  12191. },
  12192. /**
  12193. * Internal pointerLockChange handler.
  12194. * @method Phaser.Mouse#pointerLockChange
  12195. * @param {pointerlockchange} event - The native event from the browser. This gets stored in Mouse.event.
  12196. */
  12197. pointerLockChange: function (event) {
  12198. var element = this.game.stage.canvas;
  12199. if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element)
  12200. {
  12201. // Pointer was successfully locked
  12202. this.locked = true;
  12203. this.pointerLock.dispatch(true, event);
  12204. }
  12205. else
  12206. {
  12207. // Pointer was unlocked
  12208. this.locked = false;
  12209. this.pointerLock.dispatch(false, event);
  12210. }
  12211. },
  12212. /**
  12213. * Internal release pointer lock handler.
  12214. * @method Phaser.Mouse#releasePointerLock
  12215. */
  12216. releasePointerLock: function () {
  12217. document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
  12218. document.exitPointerLock();
  12219. document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
  12220. document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
  12221. document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  12222. },
  12223. /**
  12224. * Stop the event listeners.
  12225. * @method Phaser.Mouse#stop
  12226. */
  12227. stop: function () {
  12228. document.removeEventListener('mousedown', this._onMouseDown, true);
  12229. document.removeEventListener('mousemove', this._onMouseMove, true);
  12230. document.removeEventListener('mouseup', this._onMouseUp, true);
  12231. }
  12232. };
  12233. /**
  12234. * @author Richard Davey <rich@photonstorm.com>
  12235. * @copyright 2013 Photon Storm Ltd.
  12236. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12237. */
  12238. /**
  12239. * Phaser - MSPointer constructor.
  12240. *
  12241. * @class Phaser.MSPointer
  12242. * @classdesc The MSPointer class handles touch interactions with the game and the resulting Pointer objects.
  12243. * It will work only in Internet Explorer 10 and Windows Store or Windows Phone 8 apps using JavaScript.
  12244. * http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx
  12245. * @constructor
  12246. * @param {Phaser.Game} game - A reference to the currently running game.
  12247. */
  12248. Phaser.MSPointer = function (game) {
  12249. /**
  12250. * @property {Phaser.Game} game - A reference to the currently running game.
  12251. */
  12252. this.game = game;
  12253. /**
  12254. * @property {Object} callbackContext - The context under which callbacks are called (defaults to game).
  12255. */
  12256. this.callbackContext = this.game;
  12257. /**
  12258. * You can disable all Input by setting disabled = true. While set all new input related events will be ignored.
  12259. * @property {boolean} disabled
  12260. */
  12261. this.disabled = false;
  12262. /**
  12263. * @property {function} _onMSPointerDown - Internal function to handle MSPointer events.
  12264. * @private
  12265. */
  12266. this._onMSPointerDown = null;
  12267. /**
  12268. * @property {function} _onMSPointerMove - Internal function to handle MSPointer events.
  12269. * @private
  12270. */
  12271. this._onMSPointerMove = null;
  12272. /**
  12273. * @property {function} _onMSPointerUp - Internal function to handle MSPointer events.
  12274. * @private
  12275. */
  12276. this._onMSPointerUp = null;
  12277. };
  12278. Phaser.MSPointer.prototype = {
  12279. /**
  12280. * Starts the event listeners running.
  12281. * @method Phaser.MSPointer#start
  12282. */
  12283. start: function () {
  12284. var _this = this;
  12285. if (this.game.device.mspointer === true)
  12286. {
  12287. this._onMSPointerDown = function (event) {
  12288. return _this.onPointerDown(event);
  12289. };
  12290. this._onMSPointerMove = function (event) {
  12291. return _this.onPointerMove(event);
  12292. };
  12293. this._onMSPointerUp = function (event) {
  12294. return _this.onPointerUp(event);
  12295. };
  12296. this.game.renderer.view.addEventListener('MSPointerDown', this._onMSPointerDown, false);
  12297. this.game.renderer.view.addEventListener('MSPointerMove', this._onMSPointerMove, false);
  12298. this.game.renderer.view.addEventListener('MSPointerUp', this._onMSPointerUp, false);
  12299. // IE11+ uses non-prefix events
  12300. this.game.renderer.view.addEventListener('pointerDown', this._onMSPointerDown, false);
  12301. this.game.renderer.view.addEventListener('pointerMove', this._onMSPointerMove, false);
  12302. this.game.renderer.view.addEventListener('pointerUp', this._onMSPointerUp, false);
  12303. this.game.renderer.view.style['-ms-content-zooming'] = 'none';
  12304. this.game.renderer.view.style['-ms-touch-action'] = 'none';
  12305. }
  12306. },
  12307. /**
  12308. * The function that handles the PointerDown event.
  12309. * @method Phaser.MSPointer#onPointerDown
  12310. * @param {PointerEvent} event
  12311. */
  12312. onPointerDown: function (event) {
  12313. if (this.game.input.disabled || this.disabled)
  12314. {
  12315. return;
  12316. }
  12317. event.preventDefault();
  12318. event.identifier = event.pointerId;
  12319. this.game.input.startPointer(event);
  12320. },
  12321. /**
  12322. * The function that handles the PointerMove event.
  12323. * @method Phaser.MSPointer#onPointerMove
  12324. * @param {PointerEvent } event
  12325. */
  12326. onPointerMove: function (event) {
  12327. if (this.game.input.disabled || this.disabled)
  12328. {
  12329. return;
  12330. }
  12331. event.preventDefault();
  12332. event.identifier = event.pointerId;
  12333. this.game.input.updatePointer(event);
  12334. },
  12335. /**
  12336. * The function that handles the PointerUp event.
  12337. * @method Phaser.MSPointer#onPointerUp
  12338. * @param {PointerEvent} event
  12339. */
  12340. onPointerUp: function (event) {
  12341. if (this.game.input.disabled || this.disabled)
  12342. {
  12343. return;
  12344. }
  12345. event.preventDefault();
  12346. event.identifier = event.pointerId;
  12347. this.game.input.stopPointer(event);
  12348. },
  12349. /**
  12350. * Stop the event listeners.
  12351. * @method Phaser.MSPointer#stop
  12352. */
  12353. stop: function () {
  12354. this.game.stage.canvas.removeEventListener('MSPointerDown', this._onMSPointerDown);
  12355. this.game.stage.canvas.removeEventListener('MSPointerMove', this._onMSPointerMove);
  12356. this.game.stage.canvas.removeEventListener('MSPointerUp', this._onMSPointerUp);
  12357. this.game.stage.canvas.removeEventListener('pointerDown', this._onMSPointerDown);
  12358. this.game.stage.canvas.removeEventListener('pointerMove', this._onMSPointerMove);
  12359. this.game.stage.canvas.removeEventListener('pointerUp', this._onMSPointerUp);
  12360. }
  12361. };
  12362. /**
  12363. * @author Richard Davey <rich@photonstorm.com>
  12364. * @copyright 2013 Photon Storm Ltd.
  12365. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12366. */
  12367. /**
  12368. * Phaser - Pointer constructor.
  12369. *
  12370. * @class Phaser.Pointer
  12371. * @classdesc A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen.
  12372. * @constructor
  12373. * @param {Phaser.Game} game - A reference to the currently running game.
  12374. * @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
  12375. */
  12376. Phaser.Pointer = function (game, id) {
  12377. /**
  12378. * @property {Phaser.Game} game - A reference to the currently running game.
  12379. */
  12380. this.game = game;
  12381. /**
  12382. * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
  12383. */
  12384. this.id = id;
  12385. /**
  12386. * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event.
  12387. * @private
  12388. * @default
  12389. */
  12390. this._holdSent = false;
  12391. /**
  12392. * @property {array} _history - Local private variable storing the short-term history of pointer movements.
  12393. * @private
  12394. */
  12395. this._history = [];
  12396. /**
  12397. * @property {number} _lastDrop - Local private variable storing the time at which the next history drop should occur.
  12398. * @private
  12399. * @default
  12400. */
  12401. this._nextDrop = 0;
  12402. /**
  12403. * @property {boolean} _stateReset - Monitor events outside of a state reset loop.
  12404. * @private
  12405. * @default
  12406. */
  12407. this._stateReset = false;
  12408. /**
  12409. * @property {boolean} withinGame - true if the Pointer is within the game area, otherwise false.
  12410. */
  12411. this.withinGame = false;
  12412. /**
  12413. * @property {number} clientX - The horizontal coordinate of point relative to the viewport in pixels, excluding any scroll offset.
  12414. * @default
  12415. */
  12416. this.clientX = -1;
  12417. /**
  12418. * @property {number} clientY - The vertical coordinate of point relative to the viewport in pixels, excluding any scroll offset.
  12419. * @default
  12420. */
  12421. this.clientY = -1;
  12422. /**
  12423. * @property {number} pageX - The horizontal coordinate of point relative to the viewport in pixels, including any scroll offset.
  12424. * @default
  12425. */
  12426. this.pageX = -1;
  12427. /**
  12428. * @property {number} pageY - The vertical coordinate of point relative to the viewport in pixels, including any scroll offset.
  12429. * @default
  12430. */
  12431. this.pageY = -1;
  12432. /**
  12433. * @property {number} screenX - The horizontal coordinate of point relative to the screen in pixels.
  12434. * @default
  12435. */
  12436. this.screenX = -1;
  12437. /**
  12438. * @property {number} screenY - The vertical coordinate of point relative to the screen in pixels.
  12439. * @default
  12440. */
  12441. this.screenY = -1;
  12442. /**
  12443. * @property {number} x - The horizontal coordinate of point relative to the game element. This value is automatically scaled based on game size.
  12444. * @default
  12445. */
  12446. this.x = -1;
  12447. /**
  12448. * @property {number} y - The vertical coordinate of point relative to the game element. This value is automatically scaled based on game size.
  12449. * @default
  12450. */
  12451. this.y = -1;
  12452. /**
  12453. * @property {boolean} isMouse - If the Pointer is a mouse this is true, otherwise false.
  12454. * @default
  12455. */
  12456. this.isMouse = false;
  12457. /**
  12458. * @property {boolean} isDown - If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
  12459. * @default
  12460. */
  12461. this.isDown = false;
  12462. /**
  12463. * @property {boolean} isUp - If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true.
  12464. * @default
  12465. */
  12466. this.isUp = true;
  12467. /**
  12468. * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen.
  12469. * @default
  12470. */
  12471. this.timeDown = 0;
  12472. /**
  12473. * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen.
  12474. * @default
  12475. */
  12476. this.timeUp = 0;
  12477. /**
  12478. * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked.
  12479. * @default
  12480. */
  12481. this.previousTapTime = 0;
  12482. /**
  12483. * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen.
  12484. * @default
  12485. */
  12486. this.totalTouches = 0;
  12487. /**
  12488. * @property {number} msSinceLastClick - The number of miliseconds since the last click.
  12489. * @default
  12490. */
  12491. this.msSinceLastClick = Number.MAX_VALUE;
  12492. /**
  12493. * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging.
  12494. * @default
  12495. */
  12496. this.targetObject = null;
  12497. /**
  12498. * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active.
  12499. * @default
  12500. */
  12501. this.active = false;
  12502. /**
  12503. * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display.
  12504. */
  12505. this.position = new Phaser.Point();
  12506. /**
  12507. * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display.
  12508. */
  12509. this.positionDown = new Phaser.Point();
  12510. /**
  12511. * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection.
  12512. * The Circle size is 44px (Apples recommended "finger tip" size).
  12513. * @property {Phaser.Circle} circle
  12514. */
  12515. this.circle = new Phaser.Circle(0, 0, 44);
  12516. if (id === 0)
  12517. {
  12518. this.isMouse = true;
  12519. }
  12520. };
  12521. Phaser.Pointer.prototype = {
  12522. /**
  12523. * Called when the Pointer is pressed onto the touchscreen.
  12524. * @method Phaser.Pointer#start
  12525. * @param {Any} event
  12526. */
  12527. start: function (event) {
  12528. this.identifier = event.identifier;
  12529. this.target = event.target;
  12530. if (typeof event.button !== 'undefined')
  12531. {
  12532. this.button = event.button;
  12533. }
  12534. // Fix to stop rogue browser plugins from blocking the visibility state event
  12535. if (this.game.paused === true && this.game.stage.scale.incorrectOrientation === false)
  12536. {
  12537. this.game.paused = false;
  12538. return this;
  12539. }
  12540. this._history.length = 0;
  12541. this.active = true;
  12542. this.withinGame = true;
  12543. this.isDown = true;
  12544. this.isUp = false;
  12545. // Work out how long it has been since the last click
  12546. this.msSinceLastClick = this.game.time.now - this.timeDown;
  12547. this.timeDown = this.game.time.now;
  12548. this._holdSent = false;
  12549. // This sets the x/y and other local values
  12550. this.move(event);
  12551. // x and y are the old values here?
  12552. this.positionDown.setTo(this.x, this.y);
  12553. if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
  12554. {
  12555. this.game.input.x = this.x;
  12556. this.game.input.y = this.y;
  12557. this.game.input.position.setTo(this.x, this.y);
  12558. this.game.input.onDown.dispatch(this, event);
  12559. this.game.input.resetSpeed(this.x, this.y);
  12560. }
  12561. this._stateReset = false;
  12562. this.totalTouches++;
  12563. if (this.isMouse === false)
  12564. {
  12565. this.game.input.currentPointers++;
  12566. }
  12567. if (this.targetObject !== null)
  12568. {
  12569. this.targetObject._touchedHandler(this);
  12570. }
  12571. return this;
  12572. },
  12573. /**
  12574. * Called internall by the Input Manager.
  12575. * @method Phaser.Pointer#update
  12576. */
  12577. update: function () {
  12578. if (this.active)
  12579. {
  12580. if (this._holdSent === false && this.duration >= this.game.input.holdRate)
  12581. {
  12582. if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
  12583. {
  12584. this.game.input.onHold.dispatch(this);
  12585. }
  12586. this._holdSent = true;
  12587. }
  12588. // Update the droppings history
  12589. if (this.game.input.recordPointerHistory && this.game.time.now >= this._nextDrop)
  12590. {
  12591. this._nextDrop = this.game.time.now + this.game.input.recordRate;
  12592. this._history.push({
  12593. x: this.position.x,
  12594. y: this.position.y
  12595. });
  12596. if (this._history.length > this.game.input.recordLimit)
  12597. {
  12598. this._history.shift();
  12599. }
  12600. }
  12601. }
  12602. },
  12603. /**
  12604. * Called when the Pointer is moved.
  12605. * @method Phaser.Pointer#move
  12606. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  12607. */
  12608. move: function (event) {
  12609. if (this.game.input.pollLocked)
  12610. {
  12611. return;
  12612. }
  12613. if (typeof event.button !== 'undefined')
  12614. {
  12615. this.button = event.button;
  12616. }
  12617. this.clientX = event.clientX;
  12618. this.clientY = event.clientY;
  12619. this.pageX = event.pageX;
  12620. this.pageY = event.pageY;
  12621. this.screenX = event.screenX;
  12622. this.screenY = event.screenY;
  12623. this.x = (this.pageX - this.game.stage.offset.x) * this.game.input.scale.x;
  12624. this.y = (this.pageY - this.game.stage.offset.y) * this.game.input.scale.y;
  12625. this.position.setTo(this.x, this.y);
  12626. this.circle.x = this.x;
  12627. this.circle.y = this.y;
  12628. if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
  12629. {
  12630. this.game.input.activePointer = this;
  12631. this.game.input.x = this.x;
  12632. this.game.input.y = this.y;
  12633. this.game.input.position.setTo(this.game.input.x, this.game.input.y);
  12634. this.game.input.circle.x = this.game.input.x;
  12635. this.game.input.circle.y = this.game.input.y;
  12636. }
  12637. // If the game is paused we don't process any target objects
  12638. if (this.game.paused)
  12639. {
  12640. return this;
  12641. }
  12642. // Easy out if we're dragging something and it still exists
  12643. if (this.targetObject !== null && this.targetObject.isDragged === true)
  12644. {
  12645. if (this.targetObject.update(this) === false)
  12646. {
  12647. this.targetObject = null;
  12648. }
  12649. return this;
  12650. }
  12651. // Work out which object is on the top
  12652. this._highestRenderOrderID = -1;
  12653. this._highestRenderObject = null;
  12654. this._highestInputPriorityID = -1;
  12655. // Just run through the linked list
  12656. if (this.game.input.interactiveItems.total > 0)
  12657. {
  12658. var currentNode = this.game.input.interactiveItems.next;
  12659. do
  12660. {
  12661. // If the object is using pixelPerfect checks, or has a higher InputManager.PriorityID OR if the priority ID is the same as the current highest AND it has a higher renderOrderID, then set it to the top
  12662. if (currentNode.pixelPerfect || currentNode.priorityID > this._highestInputPriorityID || (currentNode.priorityID == this._highestInputPriorityID && currentNode.sprite.renderOrderID > this._highestRenderOrderID))
  12663. {
  12664. if (currentNode.checkPointerOver(this))
  12665. {
  12666. // console.log('HRO set', currentNode.sprite.name);
  12667. this._highestRenderOrderID = currentNode.sprite.renderOrderID;
  12668. this._highestInputPriorityID = currentNode.priorityID;
  12669. this._highestRenderObject = currentNode;
  12670. }
  12671. }
  12672. currentNode = currentNode.next;
  12673. }
  12674. while (currentNode != null)
  12675. }
  12676. if (this._highestRenderObject == null)
  12677. {
  12678. // The pointer isn't currently over anything, check if we've got a lingering previous target
  12679. if (this.targetObject)
  12680. {
  12681. // console.log("The pointer isn't currently over anything, check if we've got a lingering previous target");
  12682. this.targetObject._pointerOutHandler(this);
  12683. this.targetObject = null;
  12684. }
  12685. }
  12686. else
  12687. {
  12688. if (this.targetObject == null)
  12689. {
  12690. // And now set the new one
  12691. // console.log('And now set the new one');
  12692. this.targetObject = this._highestRenderObject;
  12693. this._highestRenderObject._pointerOverHandler(this);
  12694. }
  12695. else
  12696. {
  12697. // We've got a target from the last update
  12698. // console.log("We've got a target from the last update");
  12699. if (this.targetObject == this._highestRenderObject)
  12700. {
  12701. // Same target as before, so update it
  12702. // console.log("Same target as before, so update it");
  12703. if (this._highestRenderObject.update(this) === false)
  12704. {
  12705. this.targetObject = null;
  12706. }
  12707. }
  12708. else
  12709. {
  12710. // The target has changed, so tell the old one we've left it
  12711. // console.log("The target has changed, so tell the old one we've left it");
  12712. this.targetObject._pointerOutHandler(this);
  12713. // And now set the new one
  12714. this.targetObject = this._highestRenderObject;
  12715. this.targetObject._pointerOverHandler(this);
  12716. }
  12717. }
  12718. }
  12719. return this;
  12720. },
  12721. /**
  12722. * Called when the Pointer leaves the target area.
  12723. * @method Phaser.Pointer#leave
  12724. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  12725. */
  12726. leave: function (event) {
  12727. this.withinGame = false;
  12728. this.move(event);
  12729. },
  12730. /**
  12731. * Called when the Pointer leaves the touchscreen.
  12732. * @method Phaser.Pointer#stop
  12733. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  12734. */
  12735. stop: function (event) {
  12736. if (this._stateReset)
  12737. {
  12738. event.preventDefault();
  12739. return;
  12740. }
  12741. this.timeUp = this.game.time.now;
  12742. if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
  12743. {
  12744. this.game.input.onUp.dispatch(this, event);
  12745. // Was it a tap?
  12746. if (this.duration >= 0 && this.duration <= this.game.input.tapRate)
  12747. {
  12748. // Was it a double-tap?
  12749. if (this.timeUp - this.previousTapTime < this.game.input.doubleTapRate)
  12750. {
  12751. // Yes, let's dispatch the signal then with the 2nd parameter set to true
  12752. this.game.input.onTap.dispatch(this, true);
  12753. }
  12754. else
  12755. {
  12756. // Wasn't a double-tap, so dispatch a single tap signal
  12757. this.game.input.onTap.dispatch(this, false);
  12758. }
  12759. this.previousTapTime = this.timeUp;
  12760. }
  12761. }
  12762. // Mouse is always active
  12763. if (this.id > 0)
  12764. {
  12765. this.active = false;
  12766. }
  12767. this.withinGame = false;
  12768. this.isDown = false;
  12769. this.isUp = true;
  12770. if (this.isMouse === false)
  12771. {
  12772. this.game.input.currentPointers--;
  12773. }
  12774. if (this.game.input.interactiveItems.total > 0)
  12775. {
  12776. var currentNode = this.game.input.interactiveItems.next;
  12777. do
  12778. {
  12779. if (currentNode)
  12780. {
  12781. currentNode._releasedHandler(this);
  12782. }
  12783. currentNode = currentNode.next;
  12784. }
  12785. while (currentNode != null)
  12786. }
  12787. if (this.targetObject)
  12788. {
  12789. this.targetObject._releasedHandler(this);
  12790. }
  12791. this.targetObject = null;
  12792. return this;
  12793. },
  12794. /**
  12795. * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate.
  12796. * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid.
  12797. * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event.
  12798. * @method Phaser.Pointer#justPressed
  12799. * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate.
  12800. * @return {boolean} true if the Pointer was pressed down within the duration given.
  12801. */
  12802. justPressed: function (duration) {
  12803. duration = duration || this.game.input.justPressedRate;
  12804. return (this.isDown === true && (this.timeDown + duration) > this.game.time.now);
  12805. },
  12806. /**
  12807. * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate.
  12808. * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid.
  12809. * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event.
  12810. * @method Phaser.Pointer#justReleased
  12811. * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate.
  12812. * @return {boolean} true if the Pointer was released within the duration given.
  12813. */
  12814. justReleased: function (duration) {
  12815. duration = duration || this.game.input.justReleasedRate;
  12816. return (this.isUp === true && (this.timeUp + duration) > this.game.time.now);
  12817. },
  12818. /**
  12819. * Resets the Pointer properties. Called by InputManager.reset when you perform a State change.
  12820. * @method Phaser.Pointer#reset
  12821. */
  12822. reset: function () {
  12823. if (this.isMouse === false)
  12824. {
  12825. this.active = false;
  12826. }
  12827. this.identifier = null;
  12828. this.isDown = false;
  12829. this.isUp = true;
  12830. this.totalTouches = 0;
  12831. this._holdSent = false;
  12832. this._history.length = 0;
  12833. this._stateReset = true;
  12834. if (this.targetObject)
  12835. {
  12836. this.targetObject._releasedHandler(this);
  12837. }
  12838. this.targetObject = null;
  12839. }
  12840. };
  12841. /**
  12842. * How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1.
  12843. * @name Phaser.Pointer#duration
  12844. * @property {number} duration - How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1.
  12845. * @readonly
  12846. */
  12847. Object.defineProperty(Phaser.Pointer.prototype, "duration", {
  12848. get: function () {
  12849. if (this.isUp)
  12850. {
  12851. return -1;
  12852. }
  12853. return this.game.time.now - this.timeDown;
  12854. }
  12855. });
  12856. /**
  12857. * Gets the X value of this Pointer in world coordinates based on the world camera.
  12858. * @name Phaser.Pointer#worldX
  12859. * @property {number} duration - The X value of this Pointer in world coordinates based on the world camera.
  12860. * @readonly
  12861. */
  12862. Object.defineProperty(Phaser.Pointer.prototype, "worldX", {
  12863. get: function () {
  12864. return this.game.world.camera.x + this.x;
  12865. }
  12866. });
  12867. /**
  12868. * Gets the Y value of this Pointer in world coordinates based on the world camera.
  12869. * @name Phaser.Pointer#worldY
  12870. * @property {number} duration - The Y value of this Pointer in world coordinates based on the world camera.
  12871. * @readonly
  12872. */
  12873. Object.defineProperty(Phaser.Pointer.prototype, "worldY", {
  12874. get: function () {
  12875. return this.game.world.camera.y + this.y;
  12876. }
  12877. });
  12878. /**
  12879. * @author Richard Davey <rich@photonstorm.com>
  12880. * @copyright 2013 Photon Storm Ltd.
  12881. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12882. */
  12883. /**
  12884. * Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch.
  12885. *
  12886. * @class Phaser.Touch
  12887. * @classdesc The Touch class handles touch interactions with the game and the resulting Pointer objects.
  12888. * @constructor
  12889. * @param {Phaser.Game} game - A reference to the currently running game.
  12890. */
  12891. Phaser.Touch = function (game) {
  12892. /**
  12893. * @property {Phaser.Game} game - A reference to the currently running game.
  12894. */
  12895. this.game = game;
  12896. /**
  12897. * @property {boolean} disabled - You can disable all Touch events by setting disabled = true. While set all new touch events will be ignored.
  12898. * @return {boolean}
  12899. */
  12900. this.disabled = false;
  12901. /**
  12902. * @property {Object} callbackContext - The context under which callbacks are called.
  12903. */
  12904. this.callbackContext = this.game;
  12905. /**
  12906. * @property {function} touchStartCallback - A callback that can be fired on a touchStart event.
  12907. */
  12908. this.touchStartCallback = null;
  12909. /**
  12910. * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event.
  12911. */
  12912. this.touchMoveCallback = null;
  12913. /**
  12914. * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event.
  12915. */
  12916. this.touchEndCallback = null;
  12917. /**
  12918. * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event.
  12919. */
  12920. this.touchEnterCallback = null;
  12921. /**
  12922. * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event.
  12923. */
  12924. this.touchLeaveCallback = null;
  12925. /**
  12926. * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event.
  12927. */
  12928. this.touchCancelCallback = null;
  12929. /**
  12930. * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it.
  12931. * @default
  12932. */
  12933. this.preventDefault = true;
  12934. /**
  12935. * @property {TouchEvent} event - The browser touch event.
  12936. */
  12937. this.event = null;
  12938. /**
  12939. * @property {function} _onTouchStart - Internal event handler reference.
  12940. * @private
  12941. */
  12942. this._onTouchStart = null;
  12943. /**
  12944. * @property {function} _onTouchMove - Internal event handler reference.
  12945. * @private
  12946. */
  12947. this._onTouchMove = null;
  12948. /**
  12949. * @property {function} _onTouchEnd - Internal event handler reference.
  12950. * @private
  12951. */
  12952. this._onTouchEnd = null;
  12953. /**
  12954. * @property {function} _onTouchEnter - Internal event handler reference.
  12955. * @private
  12956. */
  12957. this._onTouchEnter = null;
  12958. /**
  12959. * @property {function} _onTouchLeave - Internal event handler reference.
  12960. * @private
  12961. */
  12962. this._onTouchLeave = null;
  12963. /**
  12964. * @property {function} _onTouchCancel - Internal event handler reference.
  12965. * @private
  12966. */
  12967. this._onTouchCancel = null;
  12968. /**
  12969. * @property {function} _onTouchMove - Internal event handler reference.
  12970. * @private
  12971. */
  12972. this._onTouchMove = null;
  12973. };
  12974. Phaser.Touch.prototype = {
  12975. /**
  12976. * Starts the event listeners running.
  12977. * @method Phaser.Touch#start
  12978. */
  12979. start: function () {
  12980. var _this = this;
  12981. if (this.game.device.touch)
  12982. {
  12983. this._onTouchStart = function (event) {
  12984. return _this.onTouchStart(event);
  12985. };
  12986. this._onTouchMove = function (event) {
  12987. return _this.onTouchMove(event);
  12988. };
  12989. this._onTouchEnd = function (event) {
  12990. return _this.onTouchEnd(event);
  12991. };
  12992. this._onTouchEnter = function (event) {
  12993. return _this.onTouchEnter(event);
  12994. };
  12995. this._onTouchLeave = function (event) {
  12996. return _this.onTouchLeave(event);
  12997. };
  12998. this._onTouchCancel = function (event) {
  12999. return _this.onTouchCancel(event);
  13000. };
  13001. this.game.renderer.view.addEventListener('touchstart', this._onTouchStart, false);
  13002. this.game.renderer.view.addEventListener('touchmove', this._onTouchMove, false);
  13003. this.game.renderer.view.addEventListener('touchend', this._onTouchEnd, false);
  13004. this.game.renderer.view.addEventListener('touchenter', this._onTouchEnter, false);
  13005. this.game.renderer.view.addEventListener('touchleave', this._onTouchLeave, false);
  13006. this.game.renderer.view.addEventListener('touchcancel', this._onTouchCancel, false);
  13007. }
  13008. },
  13009. /**
  13010. * Consumes all touchmove events on the document (only enable this if you know you need it!).
  13011. * @method Phaser.Touch#consumeTouchMove
  13012. */
  13013. consumeDocumentTouches: function () {
  13014. this._documentTouchMove = function (event) {
  13015. event.preventDefault();
  13016. };
  13017. document.addEventListener('touchmove', this._documentTouchMove, false);
  13018. },
  13019. /**
  13020. * The internal method that handles the touchstart event from the browser.
  13021. * @method Phaser.Touch#onTouchStart
  13022. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  13023. */
  13024. onTouchStart: function (event) {
  13025. this.event = event;
  13026. if (this.touchStartCallback)
  13027. {
  13028. this.touchStartCallback.call(this.callbackContext, event);
  13029. }
  13030. if (this.game.input.disabled || this.disabled)
  13031. {
  13032. return;
  13033. }
  13034. if (this.preventDefault)
  13035. {
  13036. event.preventDefault();
  13037. }
  13038. // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
  13039. // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
  13040. // event.changedTouches = the touches that CHANGED in this event, not the total number of them
  13041. for (var i = 0; i < event.changedTouches.length; i++)
  13042. {
  13043. this.game.input.startPointer(event.changedTouches[i]);
  13044. }
  13045. },
  13046. /**
  13047. * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome).
  13048. * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears.
  13049. * @method Phaser.Touch#onTouchCancel
  13050. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  13051. */
  13052. onTouchCancel: function (event) {
  13053. this.event = event;
  13054. if (this.touchCancelCallback)
  13055. {
  13056. this.touchCancelCallback.call(this.callbackContext, event);
  13057. }
  13058. if (this.game.input.disabled || this.disabled)
  13059. {
  13060. return;
  13061. }
  13062. if (this.preventDefault)
  13063. {
  13064. event.preventDefault();
  13065. }
  13066. // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome)
  13067. // http://www.w3.org/TR/touch-events/#dfn-touchcancel
  13068. for (var i = 0; i < event.changedTouches.length; i++)
  13069. {
  13070. this.game.input.stopPointer(event.changedTouches[i]);
  13071. }
  13072. },
  13073. /**
  13074. * For touch enter and leave its a list of the touch points that have entered or left the target.
  13075. * Doesn't appear to be supported by most browsers on a canvas element yet.
  13076. * @method Phaser.Touch#onTouchEnter
  13077. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  13078. */
  13079. onTouchEnter: function (event) {
  13080. this.event = event;
  13081. if (this.touchEnterCallback)
  13082. {
  13083. this.touchEnterCallback.call(this.callbackContext, event);
  13084. }
  13085. if (this.game.input.disabled || this.disabled)
  13086. {
  13087. return;
  13088. }
  13089. if (this.preventDefault)
  13090. {
  13091. event.preventDefault();
  13092. }
  13093. /*
  13094. for (var i = 0; i < event.changedTouches.length; i++)
  13095. {
  13096. //console.log('touch enter');
  13097. }
  13098. */
  13099. },
  13100. /**
  13101. * For touch enter and leave its a list of the touch points that have entered or left the target.
  13102. * Doesn't appear to be supported by most browsers on a canvas element yet.
  13103. * @method Phaser.Touch#onTouchLeave
  13104. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  13105. */
  13106. onTouchLeave: function (event) {
  13107. this.event = event;
  13108. if (this.touchLeaveCallback)
  13109. {
  13110. this.touchLeaveCallback.call(this.callbackContext, event);
  13111. }
  13112. if (this.preventDefault)
  13113. {
  13114. event.preventDefault();
  13115. }
  13116. /*
  13117. for (var i = 0; i < event.changedTouches.length; i++)
  13118. {
  13119. //console.log('touch leave');
  13120. }
  13121. */
  13122. },
  13123. /**
  13124. * The handler for the touchmove events.
  13125. * @method Phaser.Touch#onTouchMove
  13126. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  13127. */
  13128. onTouchMove: function (event) {
  13129. this.event = event;
  13130. if (this.touchMoveCallback)
  13131. {
  13132. this.touchMoveCallback.call(this.callbackContext, event);
  13133. }
  13134. if (this.preventDefault)
  13135. {
  13136. event.preventDefault();
  13137. }
  13138. for (var i = 0; i < event.changedTouches.length; i++)
  13139. {
  13140. this.game.input.updatePointer(event.changedTouches[i]);
  13141. }
  13142. },
  13143. /**
  13144. * The handler for the touchend events.
  13145. * @method Phaser.Touch#onTouchEnd
  13146. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  13147. */
  13148. onTouchEnd: function (event) {
  13149. this.event = event;
  13150. if (this.touchEndCallback)
  13151. {
  13152. this.touchEndCallback.call(this.callbackContext, event);
  13153. }
  13154. if (this.preventDefault)
  13155. {
  13156. event.preventDefault();
  13157. }
  13158. // For touch end its a list of the touch points that have been removed from the surface
  13159. // https://developer.mozilla.org/en-US/docs/DOM/TouchList
  13160. // event.changedTouches = the touches that CHANGED in this event, not the total number of them
  13161. for (var i = 0; i < event.changedTouches.length; i++)
  13162. {
  13163. this.game.input.stopPointer(event.changedTouches[i]);
  13164. }
  13165. },
  13166. /**
  13167. * Stop the event listeners.
  13168. * @method Phaser.Touch#stop
  13169. */
  13170. stop: function () {
  13171. if (this.game.device.touch)
  13172. {
  13173. this.game.stage.canvas.removeEventListener('touchstart', this._onTouchStart);
  13174. this.game.stage.canvas.removeEventListener('touchmove', this._onTouchMove);
  13175. this.game.stage.canvas.removeEventListener('touchend', this._onTouchEnd);
  13176. this.game.stage.canvas.removeEventListener('touchenter', this._onTouchEnter);
  13177. this.game.stage.canvas.removeEventListener('touchleave', this._onTouchLeave);
  13178. this.game.stage.canvas.removeEventListener('touchcancel', this._onTouchCancel);
  13179. }
  13180. }
  13181. };
  13182. /**
  13183. * @author Richard Davey <rich@photonstorm.com>
  13184. * @copyright 2013 Photon Storm Ltd.
  13185. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  13186. */
  13187. /**
  13188. * The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite.
  13189. * @class Phaser.InputHandler
  13190. * @constructor
  13191. * @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
  13192. */
  13193. Phaser.InputHandler = function (sprite) {
  13194. /**
  13195. * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
  13196. */
  13197. this.sprite = sprite;
  13198. /**
  13199. * @property {Phaser.Game} game - A reference to the currently running game.
  13200. */
  13201. this.game = sprite.game;
  13202. /**
  13203. * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity.
  13204. * @default
  13205. */
  13206. this.enabled = false;
  13207. /**
  13208. * @property {Description} parent - Description.
  13209. * @default
  13210. */
  13211. // this.parent = null;
  13212. /**
  13213. * @property {Description} next - Linked List
  13214. * @default
  13215. */
  13216. // this.next = null;
  13217. /**
  13218. * @property {Description} prev - Description.
  13219. * @default
  13220. */
  13221. // this.prev = null;
  13222. /**
  13223. * @property {Description} last - Description.
  13224. * @default
  13225. */
  13226. // this.last = this;
  13227. /**
  13228. * @property {Description} first - Description.
  13229. * @default
  13230. */
  13231. // this.first = this;
  13232. /**
  13233. * @property {number} priorityID - The PriorityID controls which Sprite receives an Input event first if they should overlap.
  13234. * @default
  13235. */
  13236. this.priorityID = 0;
  13237. /**
  13238. * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite.
  13239. * @default
  13240. */
  13241. this.useHandCursor = false;
  13242. /**
  13243. * @property {boolean} isDragged - true if the Sprite is being currently dragged.
  13244. * @default
  13245. */
  13246. this.isDragged = false;
  13247. /**
  13248. * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally.
  13249. * @default
  13250. */
  13251. this.allowHorizontalDrag = true;
  13252. /**
  13253. * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically.
  13254. * @default
  13255. */
  13256. this.allowVerticalDrag = true;
  13257. /**
  13258. * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within.
  13259. * @default
  13260. */
  13261. this.bringToTop = false;
  13262. /**
  13263. * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset.
  13264. * @default
  13265. */
  13266. this.snapOffset = null;
  13267. /**
  13268. * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not.
  13269. * @default
  13270. */
  13271. this.snapOnDrag = false;
  13272. /**
  13273. * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release.
  13274. * @default
  13275. */
  13276. this.snapOnRelease = false;
  13277. /**
  13278. * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid.
  13279. * @default
  13280. */
  13281. this.snapX = 0;
  13282. /**
  13283. * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid.
  13284. * @default
  13285. */
  13286. this.snapY = 0;
  13287. /**
  13288. * @property {number} pixelPerfect - Should we use pixel perfect hit detection? Warning: expensive. Only enable if you really need it!
  13289. * @default
  13290. */
  13291. this.pixelPerfect = false;
  13292. /**
  13293. * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit.
  13294. * @default
  13295. */
  13296. this.pixelPerfectAlpha = 255;
  13297. /**
  13298. * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no
  13299. * @default
  13300. */
  13301. this.draggable = false;
  13302. /**
  13303. * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag.
  13304. * @default
  13305. */
  13306. this.boundsRect = null;
  13307. /**
  13308. * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag.
  13309. * @default
  13310. */
  13311. this.boundsSprite = null;
  13312. /**
  13313. * If this object is set to consume the pointer event then it will stop all propogation from this object on.
  13314. * For example if you had a stack of 6 sprites with the same priority IDs and one consumed the event, none of the others would receive it.
  13315. * @property {boolean} consumePointerEvent
  13316. * @default
  13317. */
  13318. this.consumePointerEvent = false;
  13319. /**
  13320. * @property {Phaser.Point} _tempPoint - Description.
  13321. * @private
  13322. */
  13323. this._tempPoint = new Phaser.Point();
  13324. this._pointerData = [];
  13325. this._pointerData.push({
  13326. id: 0,
  13327. x: 0,
  13328. y: 0,
  13329. isDown: false,
  13330. isUp: false,
  13331. isOver: false,
  13332. isOut: false,
  13333. timeOver: 0,
  13334. timeOut: 0,
  13335. timeDown: 0,
  13336. timeUp: 0,
  13337. downDuration: 0,
  13338. isDragged: false
  13339. });
  13340. };
  13341. Phaser.InputHandler.prototype = {
  13342. /**
  13343. * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority.
  13344. * @method Phaser.InputHandler#start
  13345. * @param {number} priority - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other.
  13346. * @param {boolean} useHandCursor - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers)
  13347. * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound.
  13348. */
  13349. start: function (priority, useHandCursor) {
  13350. priority = priority || 0;
  13351. if (typeof useHandCursor == 'undefined') { useHandCursor = false; }
  13352. // Turning on
  13353. if (this.enabled === false)
  13354. {
  13355. // Register, etc
  13356. this.game.input.interactiveItems.add(this);
  13357. this.useHandCursor = useHandCursor;
  13358. this.priorityID = priority;
  13359. for (var i = 0; i < 10; i++)
  13360. {
  13361. this._pointerData[i] = {
  13362. id: i,
  13363. x: 0,
  13364. y: 0,
  13365. isDown: false,
  13366. isUp: false,
  13367. isOver: false,
  13368. isOut: false,
  13369. timeOver: 0,
  13370. timeOut: 0,
  13371. timeDown: 0,
  13372. timeUp: 0,
  13373. downDuration: 0,
  13374. isDragged: false
  13375. };
  13376. }
  13377. this.snapOffset = new Phaser.Point();
  13378. this.enabled = true;
  13379. // Create the signals the Input component will emit
  13380. if (this.sprite.events && this.sprite.events.onInputOver == null)
  13381. {
  13382. this.sprite.events.onInputOver = new Phaser.Signal();
  13383. this.sprite.events.onInputOut = new Phaser.Signal();
  13384. this.sprite.events.onInputDown = new Phaser.Signal();
  13385. this.sprite.events.onInputUp = new Phaser.Signal();
  13386. this.sprite.events.onDragStart = new Phaser.Signal();
  13387. this.sprite.events.onDragStop = new Phaser.Signal();
  13388. }
  13389. }
  13390. return this.sprite;
  13391. },
  13392. /**
  13393. * Resets the Input Handler and disables it.
  13394. * @method Phaser.InputHandler#reset
  13395. */
  13396. reset: function () {
  13397. this.enabled = false;
  13398. for (var i = 0; i < 10; i++)
  13399. {
  13400. this._pointerData[i] = {
  13401. id: i,
  13402. x: 0,
  13403. y: 0,
  13404. isDown: false,
  13405. isUp: false,
  13406. isOver: false,
  13407. isOut: false,
  13408. timeOver: 0,
  13409. timeOut: 0,
  13410. timeDown: 0,
  13411. timeUp: 0,
  13412. downDuration: 0,
  13413. isDragged: false
  13414. };
  13415. }
  13416. },
  13417. /**
  13418. * Stops the Input Handler from running.
  13419. * @method Phaser.InputHandler#stop
  13420. */
  13421. stop: function () {
  13422. // Turning off
  13423. if (this.enabled === false)
  13424. {
  13425. return;
  13426. }
  13427. else
  13428. {
  13429. // De-register, etc
  13430. this.enabled = false;
  13431. this.game.input.interactiveItems.remove(this);
  13432. }
  13433. },
  13434. /**
  13435. * Clean up memory.
  13436. * @method Phaser.InputHandler#destroy
  13437. */
  13438. destroy: function () {
  13439. if (this.enabled)
  13440. {
  13441. this.enabled = false;
  13442. this.game.input.interactiveItems.remove(this);
  13443. this.stop();
  13444. this.sprite = null;
  13445. }
  13446. },
  13447. /**
  13448. * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite.
  13449. * This value is only set when the pointer is over this Sprite.
  13450. * @method Phaser.InputHandler#pointerX
  13451. * @param {Phaser.Pointer} pointer
  13452. * @return {number} The x coordinate of the Input pointer.
  13453. */
  13454. pointerX: function (pointer) {
  13455. pointer = pointer || 0;
  13456. return this._pointerData[pointer].x;
  13457. },
  13458. /**
  13459. * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite
  13460. * This value is only set when the pointer is over this Sprite.
  13461. * @method Phaser.InputHandler#pointerY
  13462. * @param {Phaser.Pointer} pointer
  13463. * @return {number} The y coordinate of the Input pointer.
  13464. */
  13465. pointerY: function (pointer) {
  13466. pointer = pointer || 0;
  13467. return this._pointerData[pointer].y;
  13468. },
  13469. /**
  13470. * If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
  13471. * @method Phaser.InputHandler#pointerDown
  13472. * @param {Phaser.Pointer} pointer
  13473. * @return {boolean}
  13474. */
  13475. pointerDown: function (pointer) {
  13476. pointer = pointer || 0;
  13477. return this._pointerData[pointer].isDown;
  13478. },
  13479. /**
  13480. * If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true
  13481. * @method Phaser.InputHandler#pointerUp
  13482. * @param {Phaser.Pointer} pointer
  13483. * @return {boolean}
  13484. */
  13485. pointerUp: function (pointer) {
  13486. pointer = pointer || 0;
  13487. return this._pointerData[pointer].isUp;
  13488. },
  13489. /**
  13490. * A timestamp representing when the Pointer first touched the touchscreen.
  13491. * @method Phaser.InputHandler#pointerTimeDown
  13492. * @param {Phaser.Pointer} pointer
  13493. * @return {number}
  13494. */
  13495. pointerTimeDown: function (pointer) {
  13496. pointer = pointer || 0;
  13497. return this._pointerData[pointer].timeDown;
  13498. },
  13499. /**
  13500. * A timestamp representing when the Pointer left the touchscreen.
  13501. * @method Phaser.InputHandler#pointerTimeUp
  13502. * @param {Phaser.Pointer} pointer
  13503. * @return {number}
  13504. */
  13505. pointerTimeUp: function (pointer) {
  13506. pointer = pointer || 0;
  13507. return this._pointerData[pointer].timeUp;
  13508. },
  13509. /**
  13510. * Is the Pointer over this Sprite?
  13511. * @method Phaser.InputHandler#pointerOver
  13512. * @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
  13513. * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is over this object.
  13514. */
  13515. pointerOver: function (index) {
  13516. if (this.enabled)
  13517. {
  13518. if (typeof index === 'undefined')
  13519. {
  13520. for (var i = 0; i < 10; i++)
  13521. {
  13522. if (this._pointerData[i].isOver)
  13523. {
  13524. return true;
  13525. }
  13526. }
  13527. }
  13528. else
  13529. {
  13530. return this._pointerData[index].isOver;
  13531. }
  13532. }
  13533. return false;
  13534. },
  13535. /**
  13536. * Is the Pointer outside of this Sprite?
  13537. * @method Phaser.InputHandler#pointerOut
  13538. * @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
  13539. * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object.
  13540. */
  13541. pointerOut: function (index) {
  13542. if (this.enabled)
  13543. {
  13544. if (typeof index === 'undefined')
  13545. {
  13546. for (var i = 0; i < 10; i++)
  13547. {
  13548. if (this._pointerData[i].isOut)
  13549. {
  13550. return true;
  13551. }
  13552. }
  13553. }
  13554. else
  13555. {
  13556. return this._pointerData[index].isOut;
  13557. }
  13558. }
  13559. return false;
  13560. },
  13561. /**
  13562. * A timestamp representing when the Pointer first touched the touchscreen.
  13563. * @method Phaser.InputHandler#pointerTimeOver
  13564. * @param {Phaser.Pointer} pointer
  13565. * @return {number}
  13566. */
  13567. pointerTimeOver: function (pointer) {
  13568. pointer = pointer || 0;
  13569. return this._pointerData[pointer].timeOver;
  13570. },
  13571. /**
  13572. * A timestamp representing when the Pointer left the touchscreen.
  13573. * @method Phaser.InputHandler#pointerTimeOut
  13574. * @param {Phaser.Pointer} pointer
  13575. * @return {number}
  13576. */
  13577. pointerTimeOut: function (pointer) {
  13578. pointer = pointer || 0;
  13579. return this._pointerData[pointer].timeOut;
  13580. },
  13581. /**
  13582. * Is this sprite being dragged by the mouse or not?
  13583. * @method Phaser.InputHandler#pointerTimeOut
  13584. * @param {Phaser.Pointer} pointer
  13585. * @return {number}
  13586. */
  13587. pointerDragged: function (pointer) {
  13588. pointer = pointer || 0;
  13589. return this._pointerData[pointer].isDragged;
  13590. },
  13591. /**
  13592. * Checks if the given pointer is over this Sprite.
  13593. * @method Phaser.InputHandler#checkPointerOver
  13594. * @param {Phaser.Pointer} pointer
  13595. * @return {boolean}
  13596. */
  13597. checkPointerOver: function (pointer) {
  13598. if (this.enabled === false || this.sprite.visible === false || (this.sprite.group && this.sprite.group.visible === false))
  13599. {
  13600. return false;
  13601. }
  13602. this.sprite.getLocalUnmodifiedPosition(this._tempPoint, pointer.x, pointer.y);
  13603. if (this._tempPoint.x >= 0 && this._tempPoint.x <= this.sprite.currentFrame.width && this._tempPoint.y >= 0 && this._tempPoint.y <= this.sprite.currentFrame.height)
  13604. {
  13605. if (this.pixelPerfect)
  13606. {
  13607. return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
  13608. }
  13609. else
  13610. {
  13611. return true;
  13612. }
  13613. }
  13614. },
  13615. /**
  13616. * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to.
  13617. * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true.
  13618. * @method Phaser.InputHandler#checkPixel
  13619. * @param {number} x - The x coordinate to check.
  13620. * @param {number} y - The y coordinate to check.
  13621. * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha
  13622. */
  13623. checkPixel: function (x, y) {
  13624. // Grab a pixel from our image into the hitCanvas and then test it
  13625. if (this.sprite.texture.baseTexture.source)
  13626. {
  13627. this.game.input.hitContext.clearRect(0, 0, 1, 1);
  13628. x += this.sprite.texture.frame.x;
  13629. y += this.sprite.texture.frame.y;
  13630. this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1);
  13631. var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1);
  13632. if (rgb.data[3] >= this.pixelPerfectAlpha)
  13633. {
  13634. return true;
  13635. }
  13636. }
  13637. return false;
  13638. },
  13639. /**
  13640. * Update.
  13641. * @method Phaser.InputHandler#update
  13642. * @param {Phaser.Pointer} pointer
  13643. */
  13644. update: function (pointer) {
  13645. if (this.enabled === false || this.sprite.visible === false || (this.sprite.group && this.sprite.group.visible === false))
  13646. {
  13647. this._pointerOutHandler(pointer);
  13648. return false;
  13649. }
  13650. if (this.draggable && this._draggedPointerID == pointer.id)
  13651. {
  13652. return this.updateDrag(pointer);
  13653. }
  13654. else if (this._pointerData[pointer.id].isOver === true)
  13655. {
  13656. if (this.checkPointerOver(pointer))
  13657. {
  13658. this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
  13659. this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
  13660. return true;
  13661. }
  13662. else
  13663. {
  13664. this._pointerOutHandler(pointer);
  13665. return false;
  13666. }
  13667. }
  13668. },
  13669. /**
  13670. * Internal method handling the pointer over event.
  13671. * @method Phaser.InputHandler#_pointerOverHandler
  13672. * @private
  13673. * @param {Phaser.Pointer} pointer
  13674. */
  13675. _pointerOverHandler: function (pointer) {
  13676. if (this._pointerData[pointer.id].isOver === false)
  13677. {
  13678. this._pointerData[pointer.id].isOver = true;
  13679. this._pointerData[pointer.id].isOut = false;
  13680. this._pointerData[pointer.id].timeOver = this.game.time.now;
  13681. this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
  13682. this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
  13683. if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
  13684. {
  13685. this.game.stage.canvas.style.cursor = "pointer";
  13686. }
  13687. this.sprite.events.onInputOver.dispatch(this.sprite, pointer);
  13688. }
  13689. },
  13690. /**
  13691. * Internal method handling the pointer out event.
  13692. * @method Phaser.InputHandler#_pointerOutHandler
  13693. * @private
  13694. * @param {Phaser.Pointer} pointer
  13695. */
  13696. _pointerOutHandler: function (pointer) {
  13697. this._pointerData[pointer.id].isOver = false;
  13698. this._pointerData[pointer.id].isOut = true;
  13699. this._pointerData[pointer.id].timeOut = this.game.time.now;
  13700. if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
  13701. {
  13702. this.game.stage.canvas.style.cursor = "default";
  13703. }
  13704. if (this.sprite && this.sprite.events)
  13705. {
  13706. this.sprite.events.onInputOut.dispatch(this.sprite, pointer);
  13707. }
  13708. },
  13709. /**
  13710. * Internal method handling the touched event.
  13711. * @method Phaser.InputHandler#_touchedHandler
  13712. * @private
  13713. * @param {Phaser.Pointer} pointer
  13714. */
  13715. _touchedHandler: function (pointer) {
  13716. if (this._pointerData[pointer.id].isDown === false && this._pointerData[pointer.id].isOver === true)
  13717. {
  13718. this._pointerData[pointer.id].isDown = true;
  13719. this._pointerData[pointer.id].isUp = false;
  13720. this._pointerData[pointer.id].timeDown = this.game.time.now;
  13721. this.sprite.events.onInputDown.dispatch(this.sprite, pointer);
  13722. // Start drag
  13723. if (this.draggable && this.isDragged === false)
  13724. {
  13725. this.startDrag(pointer);
  13726. }
  13727. if (this.bringToTop)
  13728. {
  13729. this.sprite.bringToTop();
  13730. }
  13731. }
  13732. // Consume the event?
  13733. return this.consumePointerEvent;
  13734. },
  13735. /**
  13736. * Internal method handling the pointer released event.
  13737. * @method Phaser.InputHandler#_releasedHandler
  13738. * @private
  13739. * @param {Phaser.Pointer} pointer
  13740. */
  13741. _releasedHandler: function (pointer) {
  13742. // If was previously touched by this Pointer, check if still is AND still over this item
  13743. if (this._pointerData[pointer.id].isDown && pointer.isUp)
  13744. {
  13745. this._pointerData[pointer.id].isDown = false;
  13746. this._pointerData[pointer.id].isUp = true;
  13747. this._pointerData[pointer.id].timeUp = this.game.time.now;
  13748. this._pointerData[pointer.id].downDuration = this._pointerData[pointer.id].timeUp - this._pointerData[pointer.id].timeDown;
  13749. // Only release the InputUp signal if the pointer is still over this sprite
  13750. if (this.checkPointerOver(pointer))
  13751. {
  13752. this.sprite.events.onInputUp.dispatch(this.sprite, pointer);
  13753. }
  13754. else
  13755. {
  13756. // Pointer outside the sprite? Reset the cursor
  13757. if (this.useHandCursor)
  13758. {
  13759. this.game.stage.canvas.style.cursor = "default";
  13760. }
  13761. }
  13762. // Stop drag
  13763. if (this.draggable && this.isDragged && this._draggedPointerID == pointer.id)
  13764. {
  13765. this.stopDrag(pointer);
  13766. }
  13767. }
  13768. },
  13769. /**
  13770. * Updates the Pointer drag on this Sprite.
  13771. * @method Phaser.InputHandler#updateDrag
  13772. * @param {Phaser.Pointer} pointer
  13773. * @return {boolean}
  13774. */
  13775. updateDrag: function (pointer) {
  13776. if (pointer.isUp)
  13777. {
  13778. this.stopDrag(pointer);
  13779. return false;
  13780. }
  13781. if (this.allowHorizontalDrag)
  13782. {
  13783. this.sprite.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
  13784. }
  13785. if (this.allowVerticalDrag)
  13786. {
  13787. this.sprite.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
  13788. }
  13789. if (this.boundsRect)
  13790. {
  13791. this.checkBoundsRect();
  13792. }
  13793. if (this.boundsSprite)
  13794. {
  13795. this.checkBoundsSprite();
  13796. }
  13797. if (this.snapOnDrag)
  13798. {
  13799. this.sprite.x = Math.round(this.sprite.x / this.snapX) * this.snapX;
  13800. this.sprite.y = Math.round(this.sprite.y / this.snapY) * this.snapY;
  13801. }
  13802. return true;
  13803. },
  13804. /**
  13805. * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second)
  13806. * @method Phaser.InputHandler#justOver
  13807. * @param {Phaser.Pointer} pointer
  13808. * @param {number} delay - The time below which the pointer is considered as just over.
  13809. * @return {boolean}
  13810. */
  13811. justOver: function (pointer, delay) {
  13812. pointer = pointer || 0;
  13813. delay = delay || 500;
  13814. return (this._pointerData[pointer].isOver && this.overDuration(pointer) < delay);
  13815. },
  13816. /**
  13817. * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second)
  13818. * @method Phaser.InputHandler#justOut
  13819. * @param {Phaser.Pointer} pointer
  13820. * @param {number} delay - The time below which the pointer is considered as just out.
  13821. * @return {boolean}
  13822. */
  13823. justOut: function (pointer, delay) {
  13824. pointer = pointer || 0;
  13825. delay = delay || 500;
  13826. return (this._pointerData[pointer].isOut && (this.game.time.now - this._pointerData[pointer].timeOut < delay));
  13827. },
  13828. /**
  13829. * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second)
  13830. * @method Phaser.InputHandler#justPressed
  13831. * @param {Phaser.Pointer} pointer
  13832. * @param {number} delay - The time below which the pointer is considered as just over.
  13833. * @return {boolean}
  13834. */
  13835. justPressed: function (pointer, delay) {
  13836. pointer = pointer || 0;
  13837. delay = delay || 500;
  13838. return (this._pointerData[pointer].isDown && this.downDuration(pointer) < delay);
  13839. },
  13840. /**
  13841. * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second)
  13842. * @method Phaser.InputHandler#justReleased
  13843. * @param {Phaser.Pointer} pointer
  13844. * @param {number} delay - The time below which the pointer is considered as just out.
  13845. * @return {boolean}
  13846. */
  13847. justReleased: function (pointer, delay) {
  13848. pointer = pointer || 0;
  13849. delay = delay || 500;
  13850. return (this._pointerData[pointer].isUp && (this.game.time.now - this._pointerData[pointer].timeUp < delay));
  13851. },
  13852. /**
  13853. * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
  13854. * @method Phaser.InputHandler#overDuration
  13855. * @param {Phaser.Pointer} pointer
  13856. * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over.
  13857. */
  13858. overDuration: function (pointer) {
  13859. pointer = pointer || 0;
  13860. if (this._pointerData[pointer].isOver)
  13861. {
  13862. return this.game.time.now - this._pointerData[pointer].timeOver;
  13863. }
  13864. return -1;
  13865. },
  13866. /**
  13867. * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
  13868. * @method Phaser.InputHandler#downDuration
  13869. * @param {Phaser.Pointer} pointer
  13870. * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over.
  13871. */
  13872. downDuration: function (pointer) {
  13873. pointer = pointer || 0;
  13874. if (this._pointerData[pointer].isDown)
  13875. {
  13876. return this.game.time.now - this._pointerData[pointer].timeDown;
  13877. }
  13878. return -1;
  13879. },
  13880. /**
  13881. * Make this Sprite draggable by the mouse. You can also optionally set mouseStartDragCallback and mouseStopDragCallback
  13882. * @method Phaser.InputHandler#enableDrag
  13883. * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer.
  13884. * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group.
  13885. * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box.
  13886. * @param {boolean} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed.
  13887. * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere.
  13888. * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here.
  13889. */
  13890. enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) {
  13891. if (typeof lockCenter == 'undefined') { lockCenter = false; }
  13892. if (typeof bringToTop == 'undefined') { bringToTop = false; }
  13893. if (typeof pixelPerfect == 'undefined') { pixelPerfect = false; }
  13894. if (typeof alphaThreshold == 'undefined') { alphaThreshold = 255; }
  13895. if (typeof boundsRect == 'undefined') { boundsRect = null; }
  13896. if (typeof boundsSprite == 'undefined') { boundsSprite = null; }
  13897. this._dragPoint = new Phaser.Point();
  13898. this.draggable = true;
  13899. this.bringToTop = bringToTop;
  13900. this.dragOffset = new Phaser.Point();
  13901. this.dragFromCenter = lockCenter;
  13902. this.pixelPerfect = pixelPerfect;
  13903. this.pixelPerfectAlpha = alphaThreshold;
  13904. if (boundsRect)
  13905. {
  13906. this.boundsRect = boundsRect;
  13907. }
  13908. if (boundsSprite)
  13909. {
  13910. this.boundsSprite = boundsSprite;
  13911. }
  13912. },
  13913. /**
  13914. * Stops this sprite from being able to be dragged. If it is currently the target of an active drag it will be stopped immediately. Also disables any set callbacks.
  13915. * @method Phaser.InputHandler#disableDrag
  13916. */
  13917. disableDrag: function () {
  13918. if (this._pointerData)
  13919. {
  13920. for (var i = 0; i < 10; i++)
  13921. {
  13922. this._pointerData[i].isDragged = false;
  13923. }
  13924. }
  13925. this.draggable = false;
  13926. this.isDragged = false;
  13927. this._draggedPointerID = -1;
  13928. },
  13929. /**
  13930. * Called by Pointer when drag starts on this Sprite. Should not usually be called directly.
  13931. * @method Phaser.InputHandler#startDrag
  13932. * @param {Phaser.Pointer} pointer
  13933. */
  13934. startDrag: function (pointer) {
  13935. this.isDragged = true;
  13936. this._draggedPointerID = pointer.id;
  13937. this._pointerData[pointer.id].isDragged = true;
  13938. if (this.dragFromCenter)
  13939. {
  13940. this.sprite.centerOn(pointer.x, pointer.y);
  13941. this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
  13942. }
  13943. else
  13944. {
  13945. this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
  13946. }
  13947. this.updateDrag(pointer);
  13948. if (this.bringToTop)
  13949. {
  13950. this.sprite.bringToTop();
  13951. }
  13952. this.sprite.events.onDragStart.dispatch(this.sprite, pointer);
  13953. },
  13954. /**
  13955. * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly.
  13956. * @method Phaser.InputHandler#stopDrag
  13957. * @param {Phaser.Pointer} pointer
  13958. */
  13959. stopDrag: function (pointer) {
  13960. this.isDragged = false;
  13961. this._draggedPointerID = -1;
  13962. this._pointerData[pointer.id].isDragged = false;
  13963. if (this.snapOnRelease)
  13964. {
  13965. this.sprite.x = Math.round(this.sprite.x / this.snapX) * this.snapX;
  13966. this.sprite.y = Math.round(this.sprite.y / this.snapY) * this.snapY;
  13967. }
  13968. this.sprite.events.onDragStop.dispatch(this.sprite, pointer);
  13969. this.sprite.events.onInputUp.dispatch(this.sprite, pointer);
  13970. if (this.checkPointerOver(pointer) === false)
  13971. {
  13972. this._pointerOutHandler(pointer);
  13973. }
  13974. },
  13975. /**
  13976. * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move!
  13977. * @method Phaser.InputHandler#setDragLock
  13978. * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false.
  13979. * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false.
  13980. */
  13981. setDragLock: function (allowHorizontal, allowVertical) {
  13982. if (typeof allowHorizontal == 'undefined') { allowHorizontal = true; }
  13983. if (typeof allowVertical == 'undefined') { allowVertical = true; }
  13984. this.allowHorizontalDrag = allowHorizontal;
  13985. this.allowVerticalDrag = allowVertical;
  13986. },
  13987. /**
  13988. * Make this Sprite snap to the given grid either during drag or when it's released.
  13989. * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels.
  13990. * @method Phaser.InputHandler#enableSnap
  13991. * @param {number} snapX - The width of the grid cell to snap to.
  13992. * @param {number} snapY - The height of the grid cell to snap to.
  13993. * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged.
  13994. * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released.
  13995. */
  13996. enableSnap: function (snapX, snapY, onDrag, onRelease) {
  13997. if (typeof onDrag == 'undefined') { onDrag = true; }
  13998. if (typeof onRelease == 'undefined') { onRelease = false; }
  13999. this.snapX = snapX;
  14000. this.snapY = snapY;
  14001. this.snapOnDrag = onDrag;
  14002. this.snapOnRelease = onRelease;
  14003. },
  14004. /**
  14005. * Stops the sprite from snapping to a grid during drag or release.
  14006. * @method Phaser.InputHandler#disableSnap
  14007. */
  14008. disableSnap: function () {
  14009. this.snapOnDrag = false;
  14010. this.snapOnRelease = false;
  14011. },
  14012. /**
  14013. * Bounds Rect check for the sprite drag
  14014. * @method Phaser.InputHandler#checkBoundsRect
  14015. */
  14016. checkBoundsRect: function () {
  14017. if (this.sprite.x < this.boundsRect.left)
  14018. {
  14019. this.sprite.x = this.boundsRect.x;
  14020. }
  14021. else if ((this.sprite.x + this.sprite.width) > this.boundsRect.right)
  14022. {
  14023. this.sprite.x = this.boundsRect.right - this.sprite.width;
  14024. }
  14025. if (this.sprite.y < this.boundsRect.top)
  14026. {
  14027. this.sprite.y = this.boundsRect.top;
  14028. }
  14029. else if ((this.sprite.y + this.sprite.height) > this.boundsRect.bottom)
  14030. {
  14031. this.sprite.y = this.boundsRect.bottom - this.sprite.height;
  14032. }
  14033. },
  14034. /**
  14035. * Parent Sprite Bounds check for the sprite drag.
  14036. * @method Phaser.InputHandler#checkBoundsSprite
  14037. */
  14038. checkBoundsSprite: function () {
  14039. if (this.sprite.x < this.boundsSprite.x)
  14040. {
  14041. this.sprite.x = this.boundsSprite.x;
  14042. }
  14043. else if ((this.sprite.x + this.sprite.width) > (this.boundsSprite.x + this.boundsSprite.width))
  14044. {
  14045. this.sprite.x = (this.boundsSprite.x + this.boundsSprite.width) - this.sprite.width;
  14046. }
  14047. if (this.sprite.y < this.boundsSprite.y)
  14048. {
  14049. this.sprite.y = this.boundsSprite.y;
  14050. }
  14051. else if ((this.sprite.y + this.sprite.height) > (this.boundsSprite.y + this.boundsSprite.height))
  14052. {
  14053. this.sprite.y = (this.boundsSprite.y + this.boundsSprite.height) - this.sprite.height;
  14054. }
  14055. }
  14056. };
  14057. /**
  14058. * @author Richard Davey <rich@photonstorm.com>
  14059. * @copyright 2013 Photon Storm Ltd.
  14060. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  14061. */
  14062. /**
  14063. * @class Phaser.Events
  14064. *
  14065. * @classdesc The Events component is a collection of events fired by the parent game object.
  14066. *
  14067. * For example to tell when a Sprite has been added to a new group:
  14068. *
  14069. * ```sprite.events.onAddedToGroup.add(yourFunction, this);```
  14070. *
  14071. * Where `yourFunction` is the function you want called when this event occurs.
  14072. *
  14073. * Note that the Input related events only exist if the Sprite has had `inputEnabled` set to `true`.
  14074. *
  14075. * @constructor
  14076. *
  14077. * @param {Phaser.Sprite} sprite - A reference to Description.
  14078. */
  14079. Phaser.Events = function (sprite) {
  14080. this.parent = sprite;
  14081. this.onAddedToGroup = new Phaser.Signal();
  14082. this.onRemovedFromGroup = new Phaser.Signal();
  14083. this.onKilled = new Phaser.Signal();
  14084. this.onRevived = new Phaser.Signal();
  14085. this.onOutOfBounds = new Phaser.Signal();
  14086. this.onInputOver = null;
  14087. this.onInputOut = null;
  14088. this.onInputDown = null;
  14089. this.onInputUp = null;
  14090. this.onDragStart = null;
  14091. this.onDragStop = null;
  14092. this.onAnimationStart = null;
  14093. this.onAnimationComplete = null;
  14094. this.onAnimationLoop = null;
  14095. };
  14096. Phaser.Events.prototype = {
  14097. destroy: function () {
  14098. this.parent = null;
  14099. this.onAddedToGroup.dispose();
  14100. this.onRemovedFromGroup.dispose();
  14101. this.onKilled.dispose();
  14102. this.onRevived.dispose();
  14103. this.onOutOfBounds.dispose();
  14104. if (this.onInputOver)
  14105. {
  14106. this.onInputOver.dispose();
  14107. this.onInputOut.dispose();
  14108. this.onInputDown.dispose();
  14109. this.onInputUp.dispose();
  14110. this.onDragStart.dispose();
  14111. this.onDragStop.dispose();
  14112. }
  14113. if (this.onAnimationStart)
  14114. {
  14115. this.onAnimationStart.dispose();
  14116. this.onAnimationComplete.dispose();
  14117. this.onAnimationLoop.dispose();
  14118. }
  14119. }
  14120. };
  14121. /**
  14122. * @author Richard Davey <rich@photonstorm.com>
  14123. * @copyright 2013 Photon Storm Ltd.
  14124. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  14125. */
  14126. /**
  14127. * The Game Object Factory is a quick way to create all of the different sorts of core objects that Phaser uses.
  14128. *
  14129. * @class Phaser.GameObjectFactory
  14130. * @constructor
  14131. * @param {Phaser.Game} game - A reference to the currently running game.
  14132. */
  14133. Phaser.GameObjectFactory = function (game) {
  14134. /**
  14135. * @property {Phaser.Game} game - A reference to the currently running Game.
  14136. */
  14137. this.game = game;
  14138. /**
  14139. * @property {Phaser.World} world - A reference to the game world.
  14140. */
  14141. this.world = this.game.world;
  14142. };
  14143. Phaser.GameObjectFactory.prototype = {
  14144. /**
  14145. * Adds an existing object to the game world.
  14146. * @method Phaser.GameObjectFactory#existing
  14147. * @param {*} object - An instance of Phaser.Sprite, Phaser.Button or any other display object..
  14148. * @return {*} The child that was added to the Group.
  14149. */
  14150. existing: function (object) {
  14151. return this.world.add(object);
  14152. },
  14153. /**
  14154. * Create a new Sprite with specific position and sprite sheet key.
  14155. *
  14156. * @method Phaser.GameObjectFactory#sprite
  14157. * @param {number} x - X position of the new sprite.
  14158. * @param {number} y - Y position of the new sprite.
  14159. * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  14160. * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
  14161. * @returns {Phaser.Sprite} the newly created sprite object.
  14162. */
  14163. sprite: function (x, y, key, frame) {
  14164. return this.world.create(x, y, key, frame);
  14165. },
  14166. /**
  14167. * Create a new Sprite with specific position and sprite sheet key that will automatically be added as a child of the given parent.
  14168. *
  14169. * @method Phaser.GameObjectFactory#child
  14170. * @param {Phaser.Group} group - The Group to add this child to.
  14171. * @param {number} x - X position of the new sprite.
  14172. * @param {number} y - Y position of the new sprite.
  14173. * @param {string|RenderTexture} [key] - The image key as defined in the Game.Cache to use as the texture for this sprite OR a RenderTexture.
  14174. * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
  14175. * @returns {Phaser.Sprite} the newly created sprite object.
  14176. */
  14177. child: function (group, x, y, key, frame) {
  14178. return group.create(x, y, key, frame);
  14179. },
  14180. /**
  14181. * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
  14182. *
  14183. * @method Phaser.GameObjectFactory#tween
  14184. * @param {object} obj - Object the tween will be run on.
  14185. * @return {Phaser.Tween} Description.
  14186. */
  14187. tween: function (obj) {
  14188. return this.game.tweens.create(obj);
  14189. },
  14190. /**
  14191. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  14192. *
  14193. * @method Phaser.GameObjectFactory#group
  14194. * @param {*} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
  14195. * @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
  14196. * @return {Phaser.Group} The newly created group.
  14197. */
  14198. group: function (parent, name) {
  14199. return new Phaser.Group(this.game, parent, name);
  14200. },
  14201. /**
  14202. * Creates a new instance of the Sound class.
  14203. *
  14204. * @method Phaser.GameObjectFactory#audio
  14205. * @param {string} key - The Game.cache key of the sound that this object will use.
  14206. * @param {number} [volume=1] - The volume at which the sound will be played.
  14207. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  14208. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  14209. * @return {Phaser.Sound} The newly created text object.
  14210. */
  14211. audio: function (key, volume, loop, connect) {
  14212. return this.game.sound.add(key, volume, loop, connect);
  14213. },
  14214. /**
  14215. * Creates a new <code>TileSprite</code>.
  14216. *
  14217. * @method Phaser.GameObjectFactory#tileSprite
  14218. * @param {number} x - X position of the new tileSprite.
  14219. * @param {number} y - Y position of the new tileSprite.
  14220. * @param {number} width - the width of the tilesprite.
  14221. * @param {number} height - the height of the tilesprite.
  14222. * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  14223. * @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  14224. * @return {Phaser.TileSprite} The newly created tileSprite object.
  14225. */
  14226. tileSprite: function (x, y, width, height, key, frame) {
  14227. return this.world.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame));
  14228. },
  14229. /**
  14230. * Creates a new <code>Text</code>.
  14231. *
  14232. * @method Phaser.GameObjectFactory#text
  14233. * @param {number} x - X position of the new text object.
  14234. * @param {number} y - Y position of the new text object.
  14235. * @param {string} text - The actual text that will be written.
  14236. * @param {object} style - The style object containing style attributes like font, font size , etc.
  14237. * @return {Phaser.Text} The newly created text object.
  14238. */
  14239. text: function (x, y, text, style) {
  14240. return this.world.add(new Phaser.Text(this.game, x, y, text, style));
  14241. },
  14242. /**
  14243. * Creates a new <code>Button</code> object.
  14244. *
  14245. * @method Phaser.GameObjectFactory#button
  14246. * @param {number} [x] X position of the new button object.
  14247. * @param {number} [y] Y position of the new button object.
  14248. * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
  14249. * @param {function} [callback] The function to call when this button is pressed
  14250. * @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
  14251. * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
  14252. * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
  14253. * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
  14254. * @return {Phaser.Button} The newly created button object.
  14255. */
  14256. button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame) {
  14257. return this.world.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame));
  14258. },
  14259. /**
  14260. * Creates a new <code>Graphics</code> object.
  14261. *
  14262. * @method Phaser.GameObjectFactory#graphics
  14263. * @param {number} x - X position of the new graphics object.
  14264. * @param {number} y - Y position of the new graphics object.
  14265. * @return {Phaser.Graphics} The newly created graphics object.
  14266. */
  14267. graphics: function (x, y) {
  14268. return this.world.add(new Phaser.Graphics(this.game, x, y));
  14269. },
  14270. /**
  14271. * Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
  14272. * continuous effects like rain and fire. All it really does is launch Particle objects out
  14273. * at set intervals, and fixes their positions and velocities accorindgly.
  14274. *
  14275. * @method Phaser.GameObjectFactory#emitter
  14276. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  14277. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  14278. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  14279. * @return {Phaser.Emitter} The newly created emitter object.
  14280. */
  14281. emitter: function (x, y, maxParticles) {
  14282. return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles));
  14283. },
  14284. /**
  14285. * * Create a new <code>BitmapText</code>.
  14286. *
  14287. * @method Phaser.GameObjectFactory#bitmapText
  14288. * @param {number} x - X position of the new bitmapText object.
  14289. * @param {number} y - Y position of the new bitmapText object.
  14290. * @param {string} text - The actual text that will be written.
  14291. * @param {object} style - The style object containing style attributes like font, font size , etc.
  14292. * @return {Phaser.BitmapText} The newly created bitmapText object.
  14293. */
  14294. bitmapText: function (x, y, text, style) {
  14295. return this.world.add(new Phaser.BitmapText(this.game, x, y, text, style));
  14296. },
  14297. /**
  14298. * Creates a new Tilemap object.
  14299. *
  14300. * @method Phaser.GameObjectFactory#tilemap
  14301. * @param {string} key - Asset key for the JSON file.
  14302. * @return {Phaser.Tilemap} The newly created tilemap object.
  14303. */
  14304. tilemap: function (key) {
  14305. return new Phaser.Tilemap(this.game, key);
  14306. },
  14307. /**
  14308. * Creates a new Tileset object.
  14309. *
  14310. * @method Phaser.GameObjectFactory#tileset
  14311. * @param {string} key - The image key as defined in the Game.Cache to use as the tileset.
  14312. * @return {Phaser.Tileset} The newly created tileset object.
  14313. */
  14314. tileset: function (key) {
  14315. return this.game.cache.getTileset(key);
  14316. },
  14317. /**
  14318. * Creates a new Tilemap Layer object.
  14319. *
  14320. * @method Phaser.GameObjectFactory#tilemapLayer
  14321. * @param {number} x - X position of the new tilemapLayer.
  14322. * @param {number} y - Y position of the new tilemapLayer.
  14323. * @param {number} width - the width of the tilemapLayer.
  14324. * @param {number} height - the height of the tilemapLayer.
  14325. * @return {Phaser.TilemapLayer} The newly created tilemaplayer object.
  14326. */
  14327. tilemapLayer: function (x, y, width, height, tileset, tilemap, layer) {
  14328. return this.world.add(new Phaser.TilemapLayer(this.game, x, y, width, height, tileset, tilemap, layer));
  14329. },
  14330. /**
  14331. * A dynamic initially blank canvas to which images can be drawn.
  14332. *
  14333. * @method Phaser.GameObjectFactory#renderTexture
  14334. * @param {string} key - Asset key for the render texture.
  14335. * @param {number} width - the width of the render texture.
  14336. * @param {number} height - the height of the render texture.
  14337. * @return {Phaser.RenderTexture} The newly created renderTexture object.
  14338. */
  14339. renderTexture: function (key, width, height) {
  14340. var texture = new Phaser.RenderTexture(this.game, key, width, height);
  14341. this.game.cache.addRenderTexture(key, texture);
  14342. return texture;
  14343. },
  14344. /**
  14345. * A BitmapData object which can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
  14346. *
  14347. * @method Phaser.GameObjectFactory#bitmapData
  14348. * @param {number} [width=256] - The width of the BitmapData in pixels.
  14349. * @param {number} [height=256] - The height of the BitmapData in pixels.
  14350. * @return {Phaser.BitmapData} The newly created BitmapData object.
  14351. */
  14352. bitmapData: function (width, height) {
  14353. return new Phaser.BitmapData(this.game, width, height);
  14354. },
  14355. /**
  14356. * A WebGL shader/filter that can be applied to Sprites.
  14357. *
  14358. * @method Phaser.GameObjectFactory#filter
  14359. * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
  14360. * @param {any} - Whatever parameters are needed to be passed to the filter init function.
  14361. * @return {Phaser.Filter} The newly created Phaser.Filter object.
  14362. */
  14363. filter: function (filter) {
  14364. var args = Array.prototype.splice.call(arguments, 1);
  14365. var filter = new Phaser.Filter[filter](this.game);
  14366. filter.init.apply(filter, args);
  14367. return filter;
  14368. }
  14369. };
  14370. /**
  14371. * @author Richard Davey <rich@photonstorm.com>
  14372. * @copyright 2013 Photon Storm Ltd.
  14373. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  14374. */
  14375. /**
  14376. * Creates a new BitmapData object.
  14377. *
  14378. * @class Phaser.BitmapData
  14379. *
  14380. * @classdesc Note: This object is still experimental and likely to change.
  14381. *
  14382. * A BitmapData object can be thought of as a blank canvas onto which you can perform graphics operations as you would on a normal canvas,
  14383. * such as drawing lines, circles, arcs, fills and copying and setting blocks of pixel data. A single BitmapData can be used as the texture
  14384. * for multiple Sprites. So if you need to dynamically create a Sprite texture then they are a good choice. It supports the EaselJS Tiny API.
  14385. *
  14386. * @constructor
  14387. * @param {Phaser.Game} game - A reference to the currently running game.
  14388. * @param {number} [width=256] - The width of the BitmapData in pixels.
  14389. * @param {number} [height=256] - The height of the BitmapData in pixels.
  14390. */
  14391. Phaser.BitmapData = function (game, width, height) {
  14392. if (typeof width === 'undefined') { width = 256; }
  14393. if (typeof height === 'undefined') { height = 256; }
  14394. /**
  14395. * @property {Phaser.Game} game - A reference to the currently running game.
  14396. */
  14397. this.game = game;
  14398. /**
  14399. * @property {string} name - The name of the BitmapData.
  14400. */
  14401. this.name = '';
  14402. /**
  14403. * @property {number} width - The width of the BitmapData in pixels.
  14404. */
  14405. this.width = width;
  14406. /**
  14407. * @property {number} height - The height of the BitmapData in pixels.
  14408. */
  14409. this.height = height;
  14410. /**
  14411. * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws.
  14412. * @default
  14413. */
  14414. this.canvas = Phaser.Canvas.create(width, height);
  14415. /**
  14416. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  14417. * @default
  14418. */
  14419. this.context = this.canvas.getContext('2d');
  14420. /**
  14421. * @property {array} imageData - The canvas image data.
  14422. */
  14423. this.imageData = this.context.getImageData(0, 0, width, height);
  14424. /**
  14425. * @property {UInt8Clamped} pixels - A reference to the context imageData buffer.
  14426. */
  14427. if (this.imageData.data.buffer)
  14428. {
  14429. this.pixels = this.imageData.data.buffer;
  14430. }
  14431. else
  14432. {
  14433. this.pixels = this.imageData.data;
  14434. }
  14435. /**
  14436. * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture.
  14437. * @default
  14438. */
  14439. this.baseTexture = new PIXI.BaseTexture(this.canvas);
  14440. /**
  14441. * @property {PIXI.Texture} texture - The PIXI.Texture.
  14442. * @default
  14443. */
  14444. this.texture = new PIXI.Texture(this.baseTexture);
  14445. /**
  14446. * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering.
  14447. * @default
  14448. */
  14449. this.textureFrame = new Phaser.Frame(0, 0, 0, width, height, 'bitmapData', game.rnd.uuid());
  14450. /**
  14451. * @property {number} type - The const type of this object.
  14452. * @default
  14453. */
  14454. this.type = Phaser.BITMAPDATA;
  14455. this._dirty = false;
  14456. }
  14457. Phaser.BitmapData.prototype = {
  14458. /**
  14459. * Updates the given Sprite so that it uses this BitmapData as its texture.
  14460. * @method Phaser.BitmapData#add
  14461. * @param {Phaser.Sprite} sprite - The sprite to apply this texture to.
  14462. */
  14463. add: function (sprite) {
  14464. sprite.loadTexture(this);
  14465. },
  14466. /**
  14467. * Given an array of Sprites it will update each of them so that their Textures reference this BitmapData.
  14468. * @method Phaser.BitmapData#addTo
  14469. * @param {Phaser.Sprite[]} sprites - An array of Sprites to apply this texture to.
  14470. */
  14471. addTo: function (sprites) {
  14472. for (var i = 0; i < sprites.length; i++)
  14473. {
  14474. if (sprites[i].texture)
  14475. {
  14476. sprites[i].loadTexture(this);
  14477. }
  14478. }
  14479. },
  14480. /**
  14481. * Clears the BitmapData.
  14482. * @method Phaser.BitmapData#clear
  14483. */
  14484. clear: function () {
  14485. this.context.clearRect(0, 0, this.width, this.height);
  14486. this._dirty = true;
  14487. },
  14488. refreshBuffer: function () {
  14489. this.imageData = this.context.getImageData(0, 0, this.width, this.height);
  14490. this.pixels = new Int32Array(this.imageData.data.buffer);
  14491. // this.data8 = new Uint8ClampedArray(this.imageData.buffer);
  14492. // this.data32 = new Uint32Array(this.imageData.buffer);
  14493. },
  14494. /**
  14495. * Sets the color of the given pixel to the specified red, green, blue and alpha values.
  14496. * @method Phaser.BitmapData#setPixel32
  14497. * @param {number} x - The X coordinate of the pixel to be set.
  14498. * @param {number} y - The Y coordinate of the pixel to be set.
  14499. * @param {number} red - The red color value, between 0 and 0xFF (255).
  14500. * @param {number} green - The green color value, between 0 and 0xFF (255).
  14501. * @param {number} blue - The blue color value, between 0 and 0xFF (255).
  14502. * @param {number} alpha - The alpha color value, between 0 and 0xFF (255).
  14503. */
  14504. setPixel32: function (x, y, red, green, blue, alpha) {
  14505. if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
  14506. {
  14507. this.pixels[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red;
  14508. /*
  14509. if (this.isLittleEndian)
  14510. {
  14511. this.data32[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red;
  14512. }
  14513. else
  14514. {
  14515. this.data32[y * this.width + x] = (red << 24) | (green << 16) | (blue << 8) | alpha;
  14516. }
  14517. */
  14518. // this.imageData.data.set(this.data8);
  14519. this.context.putImageData(this.imageData, 0, 0);
  14520. this._dirty = true;
  14521. }
  14522. },
  14523. /**
  14524. * Sets the color of the given pixel to the specified red, green and blue values.
  14525. * @method Phaser.BitmapData#setPixel
  14526. * @param {number} x - The X coordinate of the pixel to be set.
  14527. * @param {number} y - The Y coordinate of the pixel to be set.
  14528. * @param {number} red - The red color value (between 0 and 255)
  14529. * @param {number} green - The green color value (between 0 and 255)
  14530. * @param {number} blue - The blue color value (between 0 and 255)
  14531. */
  14532. setPixel: function (x, y, red, green, blue) {
  14533. this.setPixel32(x, y, red, green, blue, 255);
  14534. },
  14535. /**
  14536. * Get a color of a specific pixel.
  14537. * @param {number} x - The X coordinate of the pixel to get.
  14538. * @param {number} y - The Y coordinate of the pixel to get.
  14539. * @return {number} A native color value integer (format: 0xRRGGBB)
  14540. */
  14541. getPixel: function (x, y) {
  14542. if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
  14543. {
  14544. return this.data32[y * this.width + x];
  14545. }
  14546. },
  14547. /**
  14548. * Get a color of a specific pixel (including alpha value).
  14549. * @param {number} x - The X coordinate of the pixel to get.
  14550. * @param {number} y - The Y coordinate of the pixel to get.
  14551. * @return {number} A native color value integer (format: 0xAARRGGBB)
  14552. */
  14553. getPixel32: function (x, y) {
  14554. if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
  14555. {
  14556. return this.data32[y * this.width + x];
  14557. }
  14558. },
  14559. /**
  14560. * Get pixels in array in a specific Rectangle.
  14561. * @param rect {Rectangle} The specific Rectangle.
  14562. * @return {array} CanvasPixelArray.
  14563. */
  14564. getPixels: function (rect) {
  14565. return this.context.getImageData(rect.x, rect.y, rect.width, rect.height);
  14566. },
  14567. /**
  14568. * Adds an arc to the path which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle
  14569. * going in the given direction by anticlockwise (defaulting to clockwise).
  14570. * @method Phaser.BitmapData#arc
  14571. * @param {number} x - The x axis of the coordinate for the arc's center
  14572. * @param {number} y - The y axis of the coordinate for the arc's center
  14573. * @param {number} radius - The arc's radius
  14574. * @param {number} startAngle - The starting point, measured from the x axis, from which it will be drawn, expressed in radians.
  14575. * @param {number} endAngle - The end arc's angle to which it will be drawn, expressed in radians.
  14576. * @param {boolean} [anticlockwise=true] - true draws the arc anticlockwise, otherwise in a clockwise direction.
  14577. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14578. */
  14579. arc: function (x, y, radius, startAngle, endAngle, anticlockwise) {
  14580. if (typeof anticlockwise === 'undefined') { anticlockwise = false; }
  14581. this._dirty = true;
  14582. this.context.arc(x, y, radius, startAngle, endAngle, anticlockwise);
  14583. return this;
  14584. },
  14585. /**
  14586. * Adds an arc with the given control points and radius, connected to the previous point by a straight line.
  14587. * @method Phaser.BitmapData#arcTo
  14588. * @param {number} x1
  14589. * @param {number} y1
  14590. * @param {number} x2
  14591. * @param {number} y2
  14592. * @param {number} radius
  14593. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14594. */
  14595. arcTo: function (x1, y1, x2, y2, radius) {
  14596. this._dirty = true;
  14597. this.context.arcTo(x1, y1, x2, y2, radius);
  14598. return this;
  14599. },
  14600. /**
  14601. * Begins a fill with the specified color. This ends the current sub-path.
  14602. * @method Phaser.BitmapData#beginFill
  14603. * @param {string} color - A CSS compatible color value (ex. "red", "#FF0000", or "rgba(255,0,0,0.5)"). Setting to null will result in no fill.
  14604. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14605. */
  14606. beginFill: function (color) {
  14607. this.fillStyle(color);
  14608. return this;
  14609. },
  14610. /**
  14611. * Begins a linear gradient fill defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For
  14612. * example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a square to display it:
  14613. *
  14614. * ```myGraphics.beginLinearGradientFill(["#000","#FFF"], [0, 1], 0, 20, 0, 120).rect(20, 20, 120, 120);```
  14615. *
  14616. * @method Phaser.BitmapData#beginLinearGradientFill
  14617. * @param {Array} colors - An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient drawing from red to blue.
  14618. * @param {Array} ratios - An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw the first color to 10% then interpolating to the second color at 90%.
  14619. * @param {number} x0 - The position of the first point defining the line that defines the gradient direction and size.
  14620. * @param {number} y0 - The position of the first point defining the line that defines the gradient direction and size.
  14621. * @param {number} x1 - The position of the second point defining the line that defines the gradient direction and size.
  14622. * @param {number} y1 - The position of the second point defining the line that defines the gradient direction and size.
  14623. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14624. */
  14625. beginLinearGradientFill: function (colors, ratios, x0, y0, x1, y1) {
  14626. var gradient = this.createLinearGradient(x0, y0, x1, y1);
  14627. for (var i = 0, len = colors.length; i < len; i++)
  14628. {
  14629. gradient.addColorStop(ratios[i], colors[i]);
  14630. }
  14631. this.fillStyle(gradient);
  14632. return this;
  14633. },
  14634. /**
  14635. * Begins a linear gradient stroke defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For
  14636. * example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a
  14637. * square to display it:
  14638. *
  14639. * ```myGraphics.setStrokeStyle(10).beginLinearGradientStroke(["#000","#FFF"], [0, 1], 0, 20, 0, 120).drawRect(20, 20, 120, 120);```
  14640. *
  14641. * @method Phaser.BitmapData#beginLinearGradientStroke
  14642. * @param {Array} colors - An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient drawing from red to blue.
  14643. * @param {Array} ratios - An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw the first color to 10% then interpolating to the second color at 90%.
  14644. * @param {number} x0 - The position of the first point defining the line that defines the gradient direction and size.
  14645. * @param {number} y0 - The position of the first point defining the line that defines the gradient direction and size.
  14646. * @param {number} x1 - The position of the second point defining the line that defines the gradient direction and size.
  14647. * @param {number} y1 - The position of the second point defining the line that defines the gradient direction and size.
  14648. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14649. */
  14650. beginLinearGradientStroke: function (colors, ratios, x0, y0, x1, y1) {
  14651. var gradient = this.createLinearGradient(x0, y0, x1, y1);
  14652. for (var i = 0, len = colors.length; i < len; i++)
  14653. {
  14654. gradient.addColorStop(ratios[i], colors[i]);
  14655. }
  14656. this.strokeStyle(gradient);
  14657. return this;
  14658. },
  14659. /**
  14660. * Begins a radial gradient stroke. This ends the current sub-path. For example, the following code defines a red to
  14661. * blue radial gradient centered at (100, 100), with a radius of 50, and draws a rectangle to display it:
  14662. *
  14663. * myGraphics.setStrokeStyle(10)
  14664. * .beginRadialGradientStroke(["#F00","#00F"], [0, 1], 100, 100, 0, 100, 100, 50)
  14665. * .drawRect(50, 90, 150, 110);
  14666. *
  14667. * @method Phaser.BitmapData#beginRadialGradientStroke
  14668. * @param {Array} colors - An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient drawing from red to blue.
  14669. * @param {Array} ratios - An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw the first color to 10% then interpolating to the second color at 90%.
  14670. * @param {number} x0 - Center position of the inner circle that defines the gradient.
  14671. * @param {number} y0 - Center position of the inner circle that defines the gradient.
  14672. * @param {number} r0 - Radius of the inner circle that defines the gradient.
  14673. * @param {number} x1 - Center position of the outer circle that defines the gradient.
  14674. * @param {number} y1 - Center position of the outer circle that defines the gradient.
  14675. * @param {number} r1 - Radius of the outer circle that defines the gradient.
  14676. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14677. */
  14678. beginRadialGradientStroke: function (colors, ratios, x0, y0, r0, x1, y1, r1) {
  14679. var gradient = this.createRadialGradient(x0, y0, r0, x1, y1, r1);
  14680. for (var i = 0, len = colors.length; i < len; i++)
  14681. {
  14682. gradient.addColorStop(ratios[i], colors[i]);
  14683. }
  14684. this.strokeStyle(gradient);
  14685. return this;
  14686. },
  14687. /**
  14688. * Starts a new path by resetting the list of sub-paths. Call this method when you want to create a new path.
  14689. * @method Phaser.BitmapData#beginPath
  14690. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14691. */
  14692. beginPath: function () {
  14693. this.context.beginPath();
  14694. return this;
  14695. },
  14696. /**
  14697. * Begins a stroke with the specified color. This ends the current sub-path.
  14698. * @method Phaser.BitmapData#beginStroke
  14699. * @param {String} color A CSS compatible color value (ex. "#FF0000", "red", or "rgba(255,0,0,0.5)"). Setting to null will result in no stroke.
  14700. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14701. */
  14702. beginStroke: function (color) {
  14703. this.strokeStyle(color);
  14704. return this;
  14705. },
  14706. /**
  14707. * Adds a bezier curve from the current context point to (x, y) using the control points (cp1x, cp1y) and (cp2x, cp2y).
  14708. * @method Phaser.BitmapData#bezierCurveTo
  14709. * @param {number} cp1x - The x axis of control point 1.
  14710. * @param {number} cp1y - The y axis of control point 1.
  14711. * @param {number} cp2x - The x axis of control point 2.
  14712. * @param {number} cp2y - The y axis of control point 2.
  14713. * @param {number} x - The x axis of the ending point.
  14714. * @param {number} y - The y axis of the ending point.
  14715. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14716. */
  14717. bezierCurveTo: function (cp1x, cp1y, cp2x, cp2y, x, y) {
  14718. this._dirty = true;
  14719. this.context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  14720. return this;
  14721. },
  14722. /**
  14723. * Draws a circle with the specified radius at (x, y).
  14724. * @method Phaser.BitmapData#circle
  14725. * @param {number} x - x coordinate center point of circle.
  14726. * @param {number} y - y coordinate center point of circle.
  14727. * @param {number} radius - Radius of circle in radians.
  14728. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14729. */
  14730. circle: function (x, y, radius) {
  14731. this.arc(x, y, radius, 0, Math.PI*2);
  14732. return this;
  14733. },
  14734. /**
  14735. * Sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black.
  14736. * @method Phaser.BitmapData#clearRect
  14737. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  14738. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  14739. * @param {number} width - The rectangles width.
  14740. * @param {number} height - The rectangles height.
  14741. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14742. */
  14743. clearRect: function (x, y, width, height) {
  14744. this._dirty = true;
  14745. this.context.clearRect(x, y, width, height);
  14746. return this;
  14747. },
  14748. /**
  14749. * Creates a clipping path from the current sub-paths. Everything drawn after clip() is called appears inside the clipping path only.
  14750. * @method Phaser.BitmapData#clip
  14751. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14752. */
  14753. clip: function () {
  14754. this._dirty = true;
  14755. this.context.clip();
  14756. return this;
  14757. },
  14758. /**
  14759. * Tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.
  14760. * @method Phaser.BitmapData#closePath
  14761. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14762. */
  14763. closePath: function () {
  14764. this._dirty = true;
  14765. this.context.closePath();
  14766. return this;
  14767. },
  14768. /**
  14769. * Creates a linear gradient with defined by an imaginary line which implies the direction of the gradient.
  14770. * Once the gradient is created colors can be inserted using the addColorStop method.
  14771. * @method Phaser.BitmapData#createLinearGradient
  14772. * @param {number} x - The x axis of the coordinate for the gradients starting point.
  14773. * @param {number} y - The y axis of the coordinate for the gradients starting point.
  14774. * @param {number} width - The width of the gradient.
  14775. * @param {number} height - The height of the gradient.
  14776. * @return {CanvasGradient} The Linear Gradient.
  14777. */
  14778. createLinearGradient: function (x, y, width, height) {
  14779. return this.context.createLinearGradient(x, y, width, height);
  14780. },
  14781. // createPattern
  14782. /**
  14783. * Creates a radial gradient.
  14784. * @method Phaser.BitmapData#createRadialGradient
  14785. * @param {number} x0
  14786. * @param {number} y0
  14787. * @param {number} r0
  14788. * @param {number} x1
  14789. * @param {number} y1
  14790. * @param {number} r1
  14791. * @return {CanvasGradient} The Radial Gradient.
  14792. */
  14793. createRadialGradient: function (x0, y0, r0, x1, y1, r1) {
  14794. return this.context.createRadialGradient(x0, y0, r0, x1, y1, r1);
  14795. },
  14796. // drawImage
  14797. // drawSystemFocusRing (?)
  14798. /**
  14799. * Draws an ellipse (oval) with a specified width (w) and height (h).
  14800. * @method Phaser.BitmapData#ellipse
  14801. * @param {number} x - x coordinate center point of ellipse.
  14802. * @param {number} y - y coordinate center point of ellipse.
  14803. * @param {number} w - height (horizontal diameter) of ellipse. The horizontal radius will be half of this number.
  14804. * @param {number} h - width (vertical diameter) of ellipse. The vertical radius will be half of this number.
  14805. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14806. */
  14807. ellipse: function (x, y, w, h) {
  14808. var k = 0.5522848;
  14809. var ox = (w / 2) * k;
  14810. var oy = (h / 2) * k;
  14811. var xe = x + w;
  14812. var ye = y + h;
  14813. var xm = x + w / 2;
  14814. var ym = y + h / 2;
  14815. this.moveTo(x, ym);
  14816. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  14817. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  14818. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  14819. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  14820. return this;
  14821. },
  14822. /**
  14823. * Fills the subpaths with the current fill style.
  14824. * @method Phaser.BitmapData#fill
  14825. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14826. */
  14827. fill: function () {
  14828. this._dirty = true;
  14829. this.context.fill();
  14830. return this;
  14831. },
  14832. /**
  14833. * Draws a filled rectangle at (x, y) position whose size is determined by width and height.
  14834. * @method Phaser.BitmapData#fillRect
  14835. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  14836. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  14837. * @param {number} width - The rectangles width.
  14838. * @param {number} height - The rectangles height.
  14839. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14840. */
  14841. fillRect: function (x, y, width, height) {
  14842. this._dirty = true;
  14843. this.context.fillRect(x, y, width, height);
  14844. return this;
  14845. },
  14846. /**
  14847. * Sets the fill style.
  14848. * @method Phaser.BitmapData#fillStyle
  14849. * @param {string} color - The fill color value in CSS format: #RRGGBB or rgba(r,g,b,a)
  14850. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14851. */
  14852. fillStyle: function (color) {
  14853. this.context.fillStyle = color;
  14854. return this;
  14855. },
  14856. // fillText
  14857. /**
  14858. * Sets the font.
  14859. * @method Phaser.BitmapData#font
  14860. * @param {DOMString} font - The font to be used for any text rendering. Default value 10px sans-serif.
  14861. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14862. */
  14863. font: function (font) {
  14864. this.context.font = font;
  14865. return this;
  14866. },
  14867. /**
  14868. * Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0 (opaque).
  14869. * @method Phaser.BitmapData#globalAlpha
  14870. * @param {number} alpha - Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0 (opaque).
  14871. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14872. */
  14873. globalAlpha: function (alpha) {
  14874. this.context.globalAlpha = alpha;
  14875. return this;
  14876. },
  14877. /**
  14878. * With globalAlpha applied this sets how shapes and images are drawn onto the existing bitmap. Possible values: source-atop, source-in, source-out,
  14879. * source-over (default), destination-atop, destination-in, destination-out, destination-over, lighter, darker, copy and xor.
  14880. * @method Phaser.BitmapData#globalCompositeOperation
  14881. * @param {DOMString} operation - The composite operation to apply.
  14882. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14883. */
  14884. globalCompositeOperation: function (operation) {
  14885. this.context.globalCompositeOperation = operation;
  14886. return this;
  14887. },
  14888. /**
  14889. * Type of endings on the end of lines. Possible values: butt (default), round, square.
  14890. * @method Phaser.BitmapData#lineCap
  14891. * @param {DOMString} style - Possible values: butt (default), round, square
  14892. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14893. */
  14894. lineCap: function (style) {
  14895. this.context.lineCap = style;
  14896. return this;
  14897. },
  14898. /**
  14899. * Specifies where to start a dasharray on a line.
  14900. * @method Phaser.BitmapData#lineDashOffset
  14901. * @param {number} offset - Specifies where to start a dasharray on a line.
  14902. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14903. */
  14904. lineDashOffset: function (offset) {
  14905. this.context.lineDashOffset = offset;
  14906. return this;
  14907. },
  14908. /**
  14909. * Defines the type of corners where two lines meet. Possible values: round, bevel, miter (default)
  14910. * @method Phaser.BitmapData#lineJoin
  14911. * @param {DOMString} join - Possible values: round, bevel, miter (default)
  14912. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14913. */
  14914. lineJoin: function (join) {
  14915. this.context.lineJoin = join;
  14916. return this;
  14917. },
  14918. /**
  14919. * Width of lines. Default 1.0
  14920. * @method Phaser.BitmapData#lineWidth
  14921. * @param {number} width - Width of lines. Default 1.0
  14922. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14923. */
  14924. lineWidth: function (width) {
  14925. this.context.lineWidth = width;
  14926. return this;
  14927. },
  14928. /**
  14929. * Default 10.
  14930. * @method Phaser.BitmapData#miterLimit
  14931. * @param {number} limit - Default 10.
  14932. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14933. */
  14934. miterLimit: function (limit) {
  14935. this.context.miterLimit = limit;
  14936. return this;
  14937. },
  14938. // getImageData
  14939. // getLineDash
  14940. // isPointInPath
  14941. // isPointInStroke
  14942. /**
  14943. * Connects the last point in the subpath to the x, y coordinates with a straight line.
  14944. * @method Phaser.BitmapData#lineTo
  14945. * @param {number} x - The x axis of the coordinate for the end of the line.
  14946. * @param {number} y - The y axis of the coordinate for the end of the line.
  14947. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14948. */
  14949. lineTo: function (x, y) {
  14950. this._dirty = true;
  14951. this.context.lineTo(x, y);
  14952. return this;
  14953. },
  14954. // measureText
  14955. /**
  14956. * Moves the starting point of a new subpath to the (x, y) coordinates.
  14957. * @method Phaser.BitmapData#moveTo
  14958. * @param {number} x - The x axis of the point.
  14959. * @param {number} y - The y axis of the point.
  14960. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14961. */
  14962. moveTo: function (x, y) {
  14963. this.context.moveTo(x, y);
  14964. return this;
  14965. },
  14966. // putImageData
  14967. /**
  14968. * Draws a quadratic curve from the current drawing point to (x, y) using the control point (cpx, cpy).
  14969. * @method Phaser.BitmapData#quadraticCurveTo
  14970. * @param {Number} cpx - The x axis of the control point.
  14971. * @param {Number} cpy - The y axis of the control point.
  14972. * @param {Number} x - The x axis of the ending point.
  14973. * @param {Number} y - The y axis of the ending point.
  14974. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14975. */
  14976. quadraticCurveTo: function(cpx, cpy, x, y) {
  14977. this._dirty = true;
  14978. this.context.quadraticCurveTo(cpx, cpy, x, y);
  14979. return this;
  14980. },
  14981. /**
  14982. * Draws a rectangle at (x, y) position whose size is determined by width and height.
  14983. * @method Phaser.BitmapData#rect
  14984. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  14985. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  14986. * @param {number} width - The rectangles width.
  14987. * @param {number} height - The rectangles height.
  14988. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14989. */
  14990. rect: function (x, y, width, height) {
  14991. this._dirty = true;
  14992. this.context.rect(x, y, width, height);
  14993. return this;
  14994. },
  14995. /**
  14996. * Restores the drawing style state to the last element on the 'state stack' saved by save().
  14997. * @method Phaser.BitmapData#restore
  14998. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  14999. */
  15000. restore: function () {
  15001. this._dirty = true;
  15002. this.context.restore();
  15003. return this;
  15004. },
  15005. /**
  15006. * Rotates the drawing context values by r radians.
  15007. * @method Phaser.BitmapData#rotate
  15008. * @param {number} angle - The angle of rotation given in radians.
  15009. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  15010. */
  15011. rotate: function (angle) {
  15012. this._dirty = true;
  15013. this.context.rotate(angle);
  15014. return this;
  15015. },
  15016. /**
  15017. * Sets the stroke style for the current sub-path. Like all drawing methods, this can be chained, so you can define
  15018. * the stroke style and color in a single line of code like so:
  15019. *
  15020. * ```myGraphics.setStrokeStyle(8,"round").beginStroke("#F00");```
  15021. *
  15022. * @method Phaser.BitmapData#setStrokeStyle
  15023. * @param {number} thickness - The width of the stroke.
  15024. * @param {string|number} [caps=0] - Indicates the type of caps to use at the end of lines. One of butt, round, or square. Defaults to "butt". Also accepts the values 0 (butt), 1 (round), and 2 (square) for use with he tiny API.
  15025. * @param {string|number} [joints=0] Specifies the type of joints that should be used where two lines meet. One of bevel, round, or miter. Defaults to "miter". Also accepts the values 0 (miter), 1 (round), and 2 (bevel) for use with the tiny API.
  15026. * @param {number} [miterLimit=10] - If joints is set to "miter", then you can specify a miter limit ratio which controls at what point a mitered joint will be clipped.
  15027. * @param {boolean} [ignoreScale=false] - If true, the stroke will be drawn at the specified thickness regardless of active transformations.
  15028. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  15029. */
  15030. setStrokeStyle: function (thickness, caps, joints, miterLimit, ignoreScale) {
  15031. if (typeof thickness === 'undefined') { thickness = 1; }
  15032. if (typeof caps === 'undefined') { caps = 'butt'; }
  15033. if (typeof joints === 'undefined') { joints = 'miter'; }
  15034. if (typeof miterLimit === 'undefined') { miterLimit = 10; }
  15035. // TODO
  15036. ignoreScale = false;
  15037. this.lineWidth(thickness);
  15038. this.lineCap(caps);
  15039. this.lineJoin(joints);
  15040. this.miterLimit(miterLimit);
  15041. return this;
  15042. },
  15043. /**
  15044. * Saves the current drawing style state using a stack so you can revert any change you make to it using restore().
  15045. * @method Phaser.BitmapData#save
  15046. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  15047. */
  15048. save: function () {
  15049. this._dirty = true;
  15050. this.context.save();
  15051. return this;
  15052. },
  15053. /**
  15054. * Scales the current drawing context.
  15055. * @method Phaser.BitmapData#scale
  15056. * @param {number} x
  15057. * @param {number} y
  15058. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  15059. */
  15060. scale: function (x, y) {
  15061. this._dirty = true;
  15062. this.context.scale(x, y);
  15063. return this;
  15064. },
  15065. /**
  15066. *
  15067. * @method Phaser.BitmapData#scrollPathIntoView
  15068. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  15069. */
  15070. scrollPathIntoView: function () {
  15071. this._dirty = true;
  15072. this.context.scrollPathIntoView();
  15073. return this;
  15074. },
  15075. // setLineDash
  15076. // setTransform
  15077. /**
  15078. * Strokes the subpaths with the current stroke style.
  15079. * @method Phaser.BitmapData#stroke
  15080. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  15081. */
  15082. stroke: function () {
  15083. this._dirty = true;
  15084. this.context.stroke();
  15085. return this;
  15086. },
  15087. /**
  15088. * Paints a rectangle which has a starting point at (x, y) and has a w width and an h height onto the canvas, using the current stroke style.
  15089. * @method Phaser.BitmapData#strokeRect
  15090. * @param {number} x - The x axis for the starting point of the rectangle.
  15091. * @param {number} y - The y axis for the starting point of the rectangle.
  15092. * @param {number} width - The rectangles width.
  15093. * @param {number} height - The rectangles height.
  15094. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  15095. */
  15096. strokeRect: function (x, y, width, height) {
  15097. this._dirty = true;
  15098. this.context.strokeRect(x, y, width, height);
  15099. return this;
  15100. },
  15101. /**
  15102. * Color or style to use for the lines around shapes. Default #000 (black).
  15103. * @method Phaser.BitmapData#strokeStyle
  15104. * @param {string} style - Color or style to use for the lines around shapes. Default #000 (black).
  15105. * @return {Phaser.BitmapData} The BitmapData instance this method was called on.
  15106. */
  15107. strokeStyle: function (style) {
  15108. this.context.strokeStyle = style;
  15109. return this;
  15110. },
  15111. // strokeText
  15112. // transform
  15113. // translate
  15114. /**
  15115. * If the game is running in WebGL this will push the texture up to the GPU if it's dirty.
  15116. * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function.
  15117. * @method Phaser.BitmapData#render
  15118. */
  15119. render: function () {
  15120. if (this._dirty)
  15121. {
  15122. // Only needed if running in WebGL, otherwise this array will never get cleared down
  15123. if (this.game.renderType == Phaser.WEBGL)
  15124. {
  15125. PIXI.texturesToUpdate.push(this.baseTexture);
  15126. }
  15127. this._dirty = false;
  15128. }
  15129. }
  15130. }
  15131. // EaselJS Tiny API emulation
  15132. /**
  15133. * Shortcut to moveTo.
  15134. * @method Phaser.BitmapData.prototype.mt
  15135. */
  15136. Phaser.BitmapData.prototype.mt = Phaser.BitmapData.prototype.moveTo;
  15137. /**
  15138. * Shortcut to lineTo.
  15139. * @method Phaser.BitmapData.prototype.mt
  15140. */
  15141. Phaser.BitmapData.prototype.lt = Phaser.BitmapData.prototype.lineTo;
  15142. /**
  15143. * Shortcut to arcTo.
  15144. * @method Phaser.BitmapData.prototype.at
  15145. */
  15146. Phaser.BitmapData.prototype.at = Phaser.BitmapData.prototype.arcTo;
  15147. /**
  15148. * Shortcut to bezierCurveTo.
  15149. * @method Phaser.BitmapData.prototype.bt
  15150. */
  15151. Phaser.BitmapData.prototype.bt = Phaser.BitmapData.prototype.bezierCurveTo;
  15152. /**
  15153. * Shortcut to quadraticCurveTo.
  15154. * @method Phaser.BitmapData.prototype.qt
  15155. */
  15156. Phaser.BitmapData.prototype.qt = Phaser.BitmapData.prototype.quadraticCurveTo;
  15157. /**
  15158. * Shortcut to arc.
  15159. * @method Phaser.BitmapData.prototype.a
  15160. */
  15161. Phaser.BitmapData.prototype.a = Phaser.BitmapData.prototype.arc;
  15162. /**
  15163. * Shortcut to rect.
  15164. * @method Phaser.BitmapData.prototype.r
  15165. */
  15166. Phaser.BitmapData.prototype.r = Phaser.BitmapData.prototype.rect;
  15167. /**
  15168. * Shortcut to closePath.
  15169. * @method Phaser.BitmapData.prototype.cp
  15170. */
  15171. Phaser.BitmapData.prototype.cp = Phaser.BitmapData.prototype.closePath;
  15172. /**
  15173. * Shortcut to clear.
  15174. * @method Phaser.BitmapData.prototype.c
  15175. */
  15176. Phaser.BitmapData.prototype.c = Phaser.BitmapData.prototype.clear;
  15177. /**
  15178. * Shortcut to beginFill.
  15179. * @method Phaser.BitmapData.prototype.f
  15180. */
  15181. Phaser.BitmapData.prototype.f = Phaser.BitmapData.prototype.beginFill;
  15182. /**
  15183. * Shortcut to beginLinearGradientFill.
  15184. * @method Phaser.BitmapData.prototype.lf
  15185. */
  15186. Phaser.BitmapData.prototype.lf = Phaser.BitmapData.prototype.beginLinearGradientFill;
  15187. /**
  15188. * Shortcut to beginRadialGradientFill.
  15189. * @method Phaser.BitmapData.prototype.rf
  15190. */
  15191. Phaser.BitmapData.prototype.rf = Phaser.BitmapData.prototype.beginRadialGradientFill;
  15192. /**
  15193. * Shortcut to beginBitmapFill.
  15194. * @method Phaser.BitmapData.prototype.bf
  15195. */
  15196. //Phaser.BitmapData.prototype.bf = Phaser.BitmapData.prototype.beginBitmapFill;
  15197. /**
  15198. * Shortcut to endFill.
  15199. * @method Phaser.BitmapData.prototype.ef
  15200. */
  15201. Phaser.BitmapData.prototype.ef = Phaser.BitmapData.prototype.endFill;
  15202. /**
  15203. * Shortcut to setStrokeStyle.
  15204. * @method Phaser.BitmapData.prototype.ss
  15205. */
  15206. Phaser.BitmapData.prototype.ss = Phaser.BitmapData.prototype.setStrokeStyle;
  15207. /**
  15208. * Shortcut to beginStroke.
  15209. * @method Phaser.BitmapData.prototype.s
  15210. */
  15211. Phaser.BitmapData.prototype.s = Phaser.BitmapData.prototype.beginStroke;
  15212. /**
  15213. * Shortcut to beginLinearGradientStroke.
  15214. * @method Phaser.BitmapData.prototype.ls
  15215. */
  15216. Phaser.BitmapData.prototype.ls = Phaser.BitmapData.prototype.beginLinearGradientStroke;
  15217. /**
  15218. * Shortcut to beginRadialGradientStroke.
  15219. * @method Phaser.BitmapData.prototype.rs
  15220. */
  15221. Phaser.BitmapData.prototype.rs = Phaser.BitmapData.prototype.beginRadialGradientStroke;
  15222. /**
  15223. * Shortcut to beginBitmapStroke.
  15224. * @method Phaser.BitmapData.prototype.bs
  15225. */
  15226. // Phaser.BitmapData.prototype.bs = Phaser.BitmapData.prototype.beginBitmapStroke;
  15227. /**
  15228. * Shortcut to endStroke.
  15229. * @method Phaser.BitmapData.prototype.es
  15230. */
  15231. // Phaser.BitmapData.prototype.es = Phaser.BitmapData.prototype.endStroke;
  15232. /**
  15233. * Shortcut to rect.
  15234. * @method Phaser.BitmapData.prototype.dr
  15235. */
  15236. Phaser.BitmapData.prototype.dr = Phaser.BitmapData.prototype.rect;
  15237. /**
  15238. * Shortcut to drawRoundRect.
  15239. * @method Phaser.BitmapData.prototype.rr
  15240. */
  15241. // Phaser.BitmapData.prototype.rr = Phaser.BitmapData.prototype.drawRoundRect;
  15242. /**
  15243. * Shortcut to drawRoundRectComplex.
  15244. * @method Phaser.BitmapData.prototype.rc
  15245. */
  15246. // Phaser.BitmapData.prototype.rc = Phaser.BitmapData.prototype.drawRoundRectComplex;
  15247. /**
  15248. * Shortcut to drawCircle.
  15249. * @method Phaser.BitmapData.prototype.dc
  15250. */
  15251. Phaser.BitmapData.prototype.dc = Phaser.BitmapData.prototype.circle;
  15252. /**
  15253. * Shortcut to drawEllipse.
  15254. * @method Phaser.BitmapData.prototype.de
  15255. */
  15256. Phaser.BitmapData.prototype.de = Phaser.BitmapData.prototype.ellipse;
  15257. /**
  15258. * Shortcut to drawPolyStar.
  15259. * @method Phaser.BitmapData.prototype.dp
  15260. */
  15261. // Phaser.BitmapData.prototype.dp = Phaser.BitmapData.prototype.drawPolyStar;
  15262. /**
  15263. * @author Richard Davey <rich@photonstorm.com>
  15264. * @copyright 2013 Photon Storm Ltd.
  15265. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  15266. */
  15267. /**
  15268. * @class Phaser.Sprite
  15269. *
  15270. * @classdesc Create a new `Sprite` object. Sprites are the lifeblood of your game, used for nearly everything visual.
  15271. *
  15272. * At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas.
  15273. * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input),
  15274. * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases.
  15275. *
  15276. * @constructor
  15277. * @param {Phaser.Game} game - A reference to the currently running game.
  15278. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  15279. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  15280. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  15281. * @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  15282. */
  15283. Phaser.Sprite = function (game, x, y, key, frame) {
  15284. x = x || 0;
  15285. y = y || 0;
  15286. key = key || null;
  15287. frame = frame || null;
  15288. /**
  15289. * @property {Phaser.Game} game - A reference to the currently running Game.
  15290. */
  15291. this.game = game;
  15292. /**
  15293. * @property {boolean} exists - If exists = false then the Sprite isn't updated by the core game loop or physics subsystem at all.
  15294. * @default
  15295. */
  15296. this.exists = true;
  15297. /**
  15298. * @property {boolean} alive - This is a handy little var your game can use to determine if a sprite is alive or not, it doesn't effect rendering.
  15299. * @default
  15300. */
  15301. this.alive = true;
  15302. /**
  15303. * @property {Phaser.Group} group - The parent Group of this Sprite. This is usually set after Sprite instantiation by the parent.
  15304. */
  15305. this.group = null;
  15306. /**
  15307. * @property {string} name - The user defined name given to this Sprite.
  15308. * @default
  15309. */
  15310. this.name = '';
  15311. /**
  15312. * @property {number} type - The const type of this object.
  15313. * @readonly
  15314. */
  15315. this.type = Phaser.SPRITE;
  15316. /**
  15317. * @property {number} renderOrderID - Used by the Renderer and Input Manager to control picking order.
  15318. * @default
  15319. */
  15320. this.renderOrderID = -1;
  15321. /**
  15322. * If you would like the Sprite to have a lifespan once 'born' you can set this to a positive value. Handy for particles, bullets, etc.
  15323. * The lifespan is decremented by game.time.elapsed each update, once it reaches zero the kill() function is called.
  15324. * @property {number} lifespan - The lifespan of the Sprite (in ms) before it will be killed.
  15325. * @default
  15326. */
  15327. this.lifespan = 0;
  15328. /**
  15329. * @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
  15330. */
  15331. this.events = new Phaser.Events(this);
  15332. /**
  15333. * @property {Phaser.AnimationManager} animations - This manages animations of the sprite. You can modify animations through it (see Phaser.AnimationManager)
  15334. */
  15335. this.animations = new Phaser.AnimationManager(this);
  15336. /**
  15337. * @property {Phaser.InputHandler} input - The Input Handler Component.
  15338. */
  15339. this.input = new Phaser.InputHandler(this);
  15340. /**
  15341. * @property {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
  15342. */
  15343. this.key = key;
  15344. /**
  15345. * @property {Phaser.Frame} currentFrame - A reference to the currently displayed frame.
  15346. */
  15347. this.currentFrame = null;
  15348. if (key instanceof Phaser.RenderTexture)
  15349. {
  15350. PIXI.Sprite.call(this, key);
  15351. this.currentFrame = this.game.cache.getTextureFrame(key.name);
  15352. }
  15353. else if (key instanceof Phaser.BitmapData)
  15354. {
  15355. PIXI.Sprite.call(this, key.texture, key.textureFrame);
  15356. this.currentFrame = key.textureFrame;
  15357. }
  15358. else if (key instanceof PIXI.Texture)
  15359. {
  15360. PIXI.Sprite.call(this, key);
  15361. this.currentFrame = frame;
  15362. }
  15363. else
  15364. {
  15365. if (key === null || typeof key === 'undefined')
  15366. {
  15367. key = '__default';
  15368. this.key = key;
  15369. }
  15370. else if (typeof key === 'string' && this.game.cache.checkImageKey(key) === false)
  15371. {
  15372. key = '__missing';
  15373. this.key = key;
  15374. }
  15375. PIXI.Sprite.call(this, PIXI.TextureCache[key]);
  15376. if (this.game.cache.isSpriteSheet(key))
  15377. {
  15378. this.animations.loadFrameData(this.game.cache.getFrameData(key));
  15379. if (frame !== null)
  15380. {
  15381. if (typeof frame === 'string')
  15382. {
  15383. this.frameName = frame;
  15384. }
  15385. else
  15386. {
  15387. this.frame = frame;
  15388. }
  15389. }
  15390. }
  15391. else
  15392. {
  15393. this.currentFrame = this.game.cache.getFrame(key);
  15394. }
  15395. }
  15396. /**
  15397. * The rectangular area from the texture that will be rendered.
  15398. * @property {Phaser.Rectangle} textureRegion
  15399. */
  15400. this.textureRegion = new Phaser.Rectangle(this.texture.frame.x, this.texture.frame.y, this.texture.frame.width, this.texture.frame.height);
  15401. /**
  15402. * The anchor sets the origin point of the texture.
  15403. * The default is 0,0 this means the textures origin is the top left
  15404. * Setting than anchor to 0.5,0.5 means the textures origin is centered
  15405. * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right
  15406. *
  15407. * @property {Phaser.Point} anchor - The anchor around which rotation and scaling takes place.
  15408. */
  15409. this.anchor = new Phaser.Point();
  15410. /**
  15411. * @property {number} x - The x coordinate in world space of this Sprite.
  15412. */
  15413. this.x = x;
  15414. /**
  15415. * @property {number} y - The y coordinate in world space of this Sprite.
  15416. */
  15417. this.y = y;
  15418. this.position.x = x;
  15419. this.position.y = y;
  15420. /**
  15421. * @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
  15422. */
  15423. this.world = new Phaser.Point(x, y);
  15424. /**
  15425. * Should this Sprite be automatically culled if out of range of the camera?
  15426. * A culled sprite has its renderable property set to 'false'.
  15427. *
  15428. * @property {boolean} autoCull - A flag indicating if the Sprite should be automatically camera culled or not.
  15429. * @default
  15430. */
  15431. this.autoCull = false;
  15432. /**
  15433. * @property {Phaser.Point} scale - The scale of the Sprite when rendered. By default it's set to 1 (no scale). You can modify it via scale.x or scale.y or scale.setTo(x, y). A value of 1 means no change to the scale, 0.5 means "half the size", 2 means "twice the size", etc.
  15434. */
  15435. this.scale = new Phaser.Point(1, 1);
  15436. /**
  15437. * @property {object} _cache - A mini cache for storing all of the calculated values.
  15438. * @private
  15439. */
  15440. this._cache = {
  15441. dirty: false,
  15442. // Transform cache
  15443. a00: -1,
  15444. a01: -1,
  15445. a02: -1,
  15446. a10: -1,
  15447. a11: -1,
  15448. a12: -1,
  15449. id: -1,
  15450. // Input specific transform cache
  15451. i01: -1,
  15452. i10: -1,
  15453. idi: -1,
  15454. // Bounds check
  15455. left: null,
  15456. right: null,
  15457. top: null,
  15458. bottom: null,
  15459. // delta cache
  15460. prevX: x,
  15461. prevY: y,
  15462. // The previous calculated position
  15463. x: -1,
  15464. y: -1,
  15465. // The actual scale values based on the worldTransform
  15466. scaleX: 1,
  15467. scaleY: 1,
  15468. // The width/height of the image, based on the un-modified frame size multiplied by the final calculated scale size
  15469. width: this.currentFrame.sourceSizeW,
  15470. height: this.currentFrame.sourceSizeH,
  15471. // The actual width/height of the image if from a trimmed atlas, multiplied by the final calculated scale size
  15472. halfWidth: Math.floor(this.currentFrame.sourceSizeW / 2),
  15473. halfHeight: Math.floor(this.currentFrame.sourceSizeH / 2),
  15474. // The width/height of the image, based on the un-modified frame size multiplied by the final calculated scale size
  15475. calcWidth: -1,
  15476. calcHeight: -1,
  15477. // The current frame details
  15478. // frameID: this.currentFrame.uuid, frameWidth: this.currentFrame.width, frameHeight: this.currentFrame.height,
  15479. frameID: -1,
  15480. frameWidth: this.currentFrame.width,
  15481. frameHeight: this.currentFrame.height,
  15482. // If this sprite visible to the camera (regardless of being set to visible or not)
  15483. cameraVisible: true,
  15484. // Crop cache
  15485. cropX: 0,
  15486. cropY: 0,
  15487. cropWidth: this.currentFrame.sourceSizeW,
  15488. cropHeight: this.currentFrame.sourceSizeH
  15489. };
  15490. /**
  15491. * @property {Phaser.Point} offset - Corner point defaults. Should not typically be modified.
  15492. */
  15493. this.offset = new Phaser.Point();
  15494. /**
  15495. * @property {Phaser.Point} center - A Point containing the center coordinate of the Sprite. Takes rotation and scale into account.
  15496. */
  15497. this.center = new Phaser.Point(x + Math.floor(this._cache.width / 2), y + Math.floor(this._cache.height / 2));
  15498. /**
  15499. * @property {Phaser.Point} topLeft - A Point containing the top left coordinate of the Sprite. Takes rotation and scale into account.
  15500. */
  15501. this.topLeft = new Phaser.Point(x, y);
  15502. /**
  15503. * @property {Phaser.Point} topRight - A Point containing the top right coordinate of the Sprite. Takes rotation and scale into account.
  15504. */
  15505. this.topRight = new Phaser.Point(x + this._cache.width, y);
  15506. /**
  15507. * @property {Phaser.Point} bottomRight - A Point containing the bottom right coordinate of the Sprite. Takes rotation and scale into account.
  15508. */
  15509. this.bottomRight = new Phaser.Point(x + this._cache.width, y + this._cache.height);
  15510. /**
  15511. * @property {Phaser.Point} bottomLeft - A Point containing the bottom left coordinate of the Sprite. Takes rotation and scale into account.
  15512. */
  15513. this.bottomLeft = new Phaser.Point(x, y + this._cache.height);
  15514. /**
  15515. * This Rectangle object fully encompasses the Sprite and is updated in real-time.
  15516. * The bounds is the full bounding area after rotation and scale have been taken into account. It should not be modified directly.
  15517. * It's used for Camera culling and physics body alignment.
  15518. * @property {Phaser.Rectangle} bounds
  15519. */
  15520. this.bounds = new Phaser.Rectangle(x, y, this._cache.width, this._cache.height);
  15521. /**
  15522. * @property {Phaser.Physics.Arcade.Body} body - By default Sprites have a Phaser.Physics Body attached to them. You can operate physics actions via this property, or null it to skip all physics updates.
  15523. */
  15524. this.body = new Phaser.Physics.Arcade.Body(this);
  15525. /**
  15526. * @property {number} health - Health value. Used in combination with damage() to allow for quick killing of Sprites.
  15527. */
  15528. this.health = 1;
  15529. /**
  15530. * @property {boolean} inWorld - This value is set to true if the Sprite is positioned within the World, otherwise false.
  15531. */
  15532. this.inWorld = Phaser.Rectangle.intersects(this.bounds, this.game.world.bounds);
  15533. /**
  15534. * @property {number} inWorldThreshold - A threshold value applied to the inWorld check. If you don't want a Sprite to be considered "out of the world" until at least 100px away for example then set it to 100.
  15535. * @default
  15536. */
  15537. this.inWorldThreshold = 0;
  15538. /**
  15539. * @property {boolean} outOfBoundsKill - If true the Sprite is killed as soon as Sprite.inWorld is false.
  15540. * @default
  15541. */
  15542. this.outOfBoundsKill = false;
  15543. /**
  15544. * @property {boolean} _outOfBoundsFired - Internal flag.
  15545. * @private
  15546. * @default
  15547. */
  15548. this._outOfBoundsFired = false;
  15549. /**
  15550. * A Sprite that is fixed to the camera ignores the position of any ancestors in the display list and uses its x/y coordinates as offsets from the top left of the camera.
  15551. * @property {boolean} fixedToCamera - Fixes this Sprite to the Camera.
  15552. * @default
  15553. */
  15554. this.fixedToCamera = false;
  15555. /**
  15556. * @property {Phaser.Point} cameraOffset - If this Sprite is fixed to the camera then use this Point to specify how far away from the Camera x/y it's rendered.
  15557. */
  15558. this.cameraOffset = new Phaser.Point();
  15559. /**
  15560. * You can crop the Sprites texture by modifying the crop properties. For example crop.width = 50 would set the Sprite to only render 50px wide.
  15561. * The crop is only applied if you have set Sprite.cropEnabled to true.
  15562. * @property {Phaser.Rectangle} crop - The crop Rectangle applied to the Sprite texture before rendering.
  15563. * @default
  15564. */
  15565. this.crop = new Phaser.Rectangle(0, 0, this._cache.width, this._cache.height);
  15566. /**
  15567. * @property {boolean} cropEnabled - If true the Sprite.crop property is used to crop the texture before render. Set to false to disable.
  15568. * @default
  15569. */
  15570. this.cropEnabled = false;
  15571. this.updateCache();
  15572. this.updateBounds();
  15573. };
  15574. // Needed to keep the PIXI.Sprite constructor in the prototype chain (as the core pixi renderer uses an instanceof check sadly)
  15575. Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype);
  15576. Phaser.Sprite.prototype.constructor = Phaser.Sprite;
  15577. /**
  15578. * Automatically called by World.preUpdate. Handles cache updates, lifespan checks, animation updates and physics updates.
  15579. *
  15580. * @method Phaser.Sprite#preUpdate
  15581. * @memberof Phaser.Sprite
  15582. */
  15583. Phaser.Sprite.prototype.preUpdate = function() {
  15584. if (!this.exists || (this.group && !this.group.exists))
  15585. {
  15586. this.renderOrderID = -1;
  15587. // Skip children if not exists
  15588. return false;
  15589. }
  15590. if (this.lifespan > 0)
  15591. {
  15592. this.lifespan -= this.game.time.elapsed;
  15593. if (this.lifespan <= 0)
  15594. {
  15595. this.kill();
  15596. return false;
  15597. }
  15598. }
  15599. this._cache.dirty = false;
  15600. if (this.visible)
  15601. {
  15602. this.renderOrderID = this.game.world.currentRenderOrderID++;
  15603. }
  15604. this.updateCache();
  15605. this.updateAnimation();
  15606. this.updateCrop();
  15607. // Re-run the camera visibility check
  15608. if (this._cache.dirty || this.world.x !== this._cache.prevX || this.world.y !== this._cache.prevY)
  15609. {
  15610. this.updateBounds();
  15611. }
  15612. if (this.body)
  15613. {
  15614. this.body.preUpdate();
  15615. }
  15616. return true;
  15617. };
  15618. /**
  15619. * Internal function called by preUpdate.
  15620. *
  15621. * @method Phaser.Sprite#updateCache
  15622. * @memberof Phaser.Sprite
  15623. */
  15624. Phaser.Sprite.prototype.updateCache = function() {
  15625. this._cache.prevX = this.world.x;
  15626. this._cache.prevY = this.world.y;
  15627. if (this.fixedToCamera)
  15628. {
  15629. this.x = this.game.camera.view.x + this.cameraOffset.x;
  15630. this.y = this.game.camera.view.y + this.cameraOffset.y;
  15631. }
  15632. this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
  15633. if (this.worldTransform[1] != this._cache.i01 || this.worldTransform[3] != this._cache.i10 || this.worldTransform[0] != this._cache.a00 || this.worldTransform[41] != this._cache.a11)
  15634. {
  15635. this._cache.a00 = this.worldTransform[0]; // scaleX a |a c tx|
  15636. this._cache.a01 = this.worldTransform[1]; // skewY c |b d ty|
  15637. this._cache.a10 = this.worldTransform[3]; // skewX b |0 0 1|
  15638. this._cache.a11 = this.worldTransform[4]; // scaleY d
  15639. this._cache.i01 = this.worldTransform[1]; // skewY c (remains non-modified for input checks)
  15640. this._cache.i10 = this.worldTransform[3]; // skewX b (remains non-modified for input checks)
  15641. this._cache.scaleX = Math.sqrt((this._cache.a00 * this._cache.a00) + (this._cache.a01 * this._cache.a01)); // round this off a bit?
  15642. this._cache.scaleY = Math.sqrt((this._cache.a10 * this._cache.a10) + (this._cache.a11 * this._cache.a11)); // round this off a bit?
  15643. this._cache.a01 *= -1;
  15644. this._cache.a10 *= -1;
  15645. this._cache.id = 1 / (this._cache.a00 * this._cache.a11 + this._cache.a01 * -this._cache.a10);
  15646. this._cache.idi = 1 / (this._cache.a00 * this._cache.a11 + this._cache.i01 * -this._cache.i10);
  15647. this._cache.dirty = true;
  15648. }
  15649. this._cache.a02 = this.worldTransform[2]; // translateX tx
  15650. this._cache.a12 = this.worldTransform[5]; // translateY ty
  15651. };
  15652. /**
  15653. * Internal function called by preUpdate.
  15654. *
  15655. * @method Phaser.Sprite#updateAnimation
  15656. * @memberof Phaser.Sprite
  15657. */
  15658. Phaser.Sprite.prototype.updateAnimation = function() {
  15659. if (this.animations.update() || (this.currentFrame && this.currentFrame.uuid != this._cache.frameID))
  15660. {
  15661. this._cache.frameID = this.currentFrame.uuid;
  15662. this._cache.frameWidth = this.texture.frame.width;
  15663. this._cache.frameHeight = this.texture.frame.height;
  15664. this._cache.width = this.currentFrame.width;
  15665. this._cache.height = this.currentFrame.height;
  15666. this._cache.halfWidth = Math.floor(this._cache.width / 2);
  15667. this._cache.halfHeight = Math.floor(this._cache.height / 2);
  15668. this._cache.dirty = true;
  15669. }
  15670. };
  15671. /**
  15672. * Internal function called by preUpdate.
  15673. *
  15674. * @method Phaser.Sprite#updateCrop
  15675. * @memberof Phaser.Sprite
  15676. */
  15677. Phaser.Sprite.prototype.updateCrop = function() {
  15678. // This only runs if crop is enabled
  15679. if (this.cropEnabled && (this.crop.width != this._cache.cropWidth || this.crop.height != this._cache.cropHeight || this.crop.x != this._cache.cropX || this.crop.y != this._cache.cropY))
  15680. {
  15681. this.crop.floorAll();
  15682. this._cache.cropX = this.crop.x;
  15683. this._cache.cropY = this.crop.y;
  15684. this._cache.cropWidth = this.crop.width;
  15685. this._cache.cropHeight = this.crop.height;
  15686. this.texture.frame = this.crop;
  15687. this.texture.width = this.crop.width;
  15688. this.texture.height = this.crop.height;
  15689. this.texture.updateFrame = true;
  15690. PIXI.Texture.frameUpdates.push(this.texture);
  15691. }
  15692. };
  15693. /**
  15694. * Internal function called by preUpdate.
  15695. *
  15696. * @method Phaser.Sprite#updateBounds
  15697. * @memberof Phaser.Sprite
  15698. */
  15699. Phaser.Sprite.prototype.updateBounds = function() {
  15700. this.offset.setTo(this._cache.a02 - (this.anchor.x * this.width), this._cache.a12 - (this.anchor.y * this.height));
  15701. this.getLocalPosition(this.center, this.offset.x + (this.width / 2), this.offset.y + (this.height / 2));
  15702. this.getLocalPosition(this.topLeft, this.offset.x, this.offset.y);
  15703. this.getLocalPosition(this.topRight, this.offset.x + this.width, this.offset.y);
  15704. this.getLocalPosition(this.bottomLeft, this.offset.x, this.offset.y + this.height);
  15705. this.getLocalPosition(this.bottomRight, this.offset.x + this.width, this.offset.y + this.height);
  15706. this._cache.left = Phaser.Math.min(this.topLeft.x, this.topRight.x, this.bottomLeft.x, this.bottomRight.x);
  15707. this._cache.right = Phaser.Math.max(this.topLeft.x, this.topRight.x, this.bottomLeft.x, this.bottomRight.x);
  15708. this._cache.top = Phaser.Math.min(this.topLeft.y, this.topRight.y, this.bottomLeft.y, this.bottomRight.y);
  15709. this._cache.bottom = Phaser.Math.max(this.topLeft.y, this.topRight.y, this.bottomLeft.y, this.bottomRight.y);
  15710. this.bounds.setTo(this._cache.left, this._cache.top, this._cache.right - this._cache.left, this._cache.bottom - this._cache.top);
  15711. this.updateFrame = true;
  15712. if (this.inWorld === false)
  15713. {
  15714. // Sprite WAS out of the screen, is it still?
  15715. this.inWorld = Phaser.Rectangle.intersects(this.bounds, this.game.world.bounds, this.inWorldThreshold);
  15716. if (this.inWorld)
  15717. {
  15718. // It's back again, reset the OOB check
  15719. this._outOfBoundsFired = false;
  15720. }
  15721. }
  15722. else
  15723. {
  15724. // Sprite WAS in the screen, has it now left?
  15725. this.inWorld = Phaser.Rectangle.intersects(this.bounds, this.game.world.bounds, this.inWorldThreshold);
  15726. if (this.inWorld === false)
  15727. {
  15728. this.events.onOutOfBounds.dispatch(this);
  15729. this._outOfBoundsFired = true;
  15730. if (this.outOfBoundsKill)
  15731. {
  15732. this.kill();
  15733. }
  15734. }
  15735. }
  15736. this._cache.cameraVisible = Phaser.Rectangle.intersects(this.game.world.camera.screenView, this.bounds, 0);
  15737. if (this.autoCull)
  15738. {
  15739. // Won't get rendered but will still get its transform updated
  15740. this.renderable = this._cache.cameraVisible;
  15741. }
  15742. // Update our physics bounds
  15743. if (this.body)
  15744. {
  15745. this.body.updateBounds(this.center.x, this.center.y, this._cache.scaleX, this._cache.scaleY);
  15746. }
  15747. };
  15748. /**
  15749. * Gets the local position of a coordinate relative to the Sprite, factoring in rotation and scale.
  15750. * Mostly only used internally.
  15751. *
  15752. * @method Phaser.Sprite#getLocalPosition
  15753. * @memberof Phaser.Sprite
  15754. * @param {Phaser.Point} p - The Point object to store the results in.
  15755. * @param {number} x - x coordinate within the Sprite to translate.
  15756. * @param {number} y - x coordinate within the Sprite to translate.
  15757. * @param {number} sx - Scale factor to be applied.
  15758. * @param {number} sy - Scale factor to be applied.
  15759. * @return {Phaser.Point} The translated point.
  15760. */
  15761. Phaser.Sprite.prototype.getLocalPosition = function(p, x, y) {
  15762. p.x = ((this._cache.a11 * this._cache.id * x + -this._cache.a01 * this._cache.id * y + (this._cache.a12 * this._cache.a01 - this._cache.a02 * this._cache.a11) * this._cache.id) * this.scale.x) + this._cache.a02;
  15763. p.y = ((this._cache.a00 * this._cache.id * y + -this._cache.a10 * this._cache.id * x + (-this._cache.a12 * this._cache.a00 + this._cache.a02 * this._cache.a10) * this._cache.id) * this.scale.y) + this._cache.a12;
  15764. return p;
  15765. };
  15766. /**
  15767. * Gets the local unmodified position of a coordinate relative to the Sprite, factoring in rotation and scale.
  15768. * Mostly only used internally by the Input Manager, but also useful for custom hit detection.
  15769. *
  15770. * @method Phaser.Sprite#getLocalUnmodifiedPosition
  15771. * @memberof Phaser.Sprite
  15772. * @param {Phaser.Point} p - The Point object to store the results in.
  15773. * @param {number} x - x coordinate within the Sprite to translate.
  15774. * @param {number} y - x coordinate within the Sprite to translate.
  15775. * @return {Phaser.Point} The translated point.
  15776. */
  15777. Phaser.Sprite.prototype.getLocalUnmodifiedPosition = function(p, gx, gy) {
  15778. p.x = (this._cache.a11 * this._cache.idi * gx + -this._cache.i01 * this._cache.idi * gy + (this._cache.a12 * this._cache.i01 - this._cache.a02 * this._cache.a11) * this._cache.idi) + (this.anchor.x * this._cache.width);
  15779. p.y = (this._cache.a00 * this._cache.idi * gy + -this._cache.i10 * this._cache.idi * gx + (-this._cache.a12 * this._cache.a00 + this._cache.a02 * this._cache.i10) * this._cache.idi) + (this.anchor.y * this._cache.height);
  15780. return p;
  15781. };
  15782. /**
  15783. * Resets the Sprite.crop value back to the frame dimensions.
  15784. *
  15785. * @method Phaser.Sprite#resetCrop
  15786. * @memberof Phaser.Sprite
  15787. */
  15788. Phaser.Sprite.prototype.resetCrop = function() {
  15789. this.crop = new Phaser.Rectangle(0, 0, this._cache.width, this._cache.height);
  15790. this.texture.setFrame(this.crop);
  15791. this.cropEnabled = false;
  15792. };
  15793. /**
  15794. * Internal function called by the World postUpdate cycle.
  15795. *
  15796. * @method Phaser.Sprite#postUpdate
  15797. * @memberof Phaser.Sprite
  15798. */
  15799. Phaser.Sprite.prototype.postUpdate = function() {
  15800. if (this.key instanceof Phaser.BitmapData && this.key._dirty)
  15801. {
  15802. this.key.render();
  15803. }
  15804. if (this.exists)
  15805. {
  15806. // The sprite is positioned in this call, after taking into consideration motion updates and collision
  15807. if (this.body)
  15808. {
  15809. this.body.postUpdate();
  15810. }
  15811. if (this.fixedToCamera)
  15812. {
  15813. this._cache.x = this.game.camera.view.x + this.cameraOffset.x;
  15814. this._cache.y = this.game.camera.view.y + this.cameraOffset.y;
  15815. }
  15816. else
  15817. {
  15818. this._cache.x = this.x;
  15819. this._cache.y = this.y;
  15820. }
  15821. this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
  15822. this.position.x = this._cache.x;
  15823. this.position.y = this._cache.y;
  15824. }
  15825. };
  15826. /**
  15827. * Changes the Texture the Sprite is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
  15828. * This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.
  15829. *
  15830. * @method Phaser.Sprite#loadTexture
  15831. * @memberof Phaser.Sprite
  15832. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
  15833. * @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  15834. */
  15835. Phaser.Sprite.prototype.loadTexture = function (key, frame) {
  15836. this.key = key;
  15837. if (key instanceof Phaser.RenderTexture)
  15838. {
  15839. this.currentFrame = this.game.cache.getTextureFrame(key.name);
  15840. }
  15841. else if (key instanceof Phaser.BitmapData)
  15842. {
  15843. this.setTexture(key.texture);
  15844. this.currentFrame = key.textureFrame;
  15845. }
  15846. else if (key instanceof PIXI.Texture)
  15847. {
  15848. this.currentFrame = frame;
  15849. }
  15850. else
  15851. {
  15852. if (typeof key === 'undefined' || this.game.cache.checkImageKey(key) === false)
  15853. {
  15854. key = '__default';
  15855. this.key = key;
  15856. }
  15857. if (this.game.cache.isSpriteSheet(key))
  15858. {
  15859. this.animations.loadFrameData(this.game.cache.getFrameData(key));
  15860. if (typeof frame !== 'undefined')
  15861. {
  15862. if (typeof frame === 'string')
  15863. {
  15864. this.frameName = frame;
  15865. }
  15866. else
  15867. {
  15868. this.frame = frame;
  15869. }
  15870. }
  15871. }
  15872. else
  15873. {
  15874. this.currentFrame = this.game.cache.getFrame(key);
  15875. this.setTexture(PIXI.TextureCache[key]);
  15876. }
  15877. }
  15878. };
  15879. /**
  15880. * Moves the sprite so its center is located on the given x and y coordinates.
  15881. * Doesn't change the anchor point of the sprite.
  15882. *
  15883. * @method Phaser.Sprite#centerOn
  15884. * @memberof Phaser.Sprite
  15885. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  15886. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  15887. * @return (Phaser.Sprite) This instance.
  15888. */
  15889. Phaser.Sprite.prototype.centerOn = function(x, y) {
  15890. this.x = x + (this.x - this.center.x);
  15891. this.y = y + (this.y - this.center.y);
  15892. return this;
  15893. };
  15894. /**
  15895. * Brings a 'dead' Sprite back to life, optionally giving it the health value specified.
  15896. * A resurrected Sprite has its alive, exists and visible properties all set to true.
  15897. * It will dispatch the onRevived event, you can listen to Sprite.events.onRevived for the signal.
  15898. *
  15899. * @method Phaser.Sprite#revive
  15900. * @memberof Phaser.Sprite
  15901. * @param {number} [health=1] - The health to give the Sprite.
  15902. * @return (Phaser.Sprite) This instance.
  15903. */
  15904. Phaser.Sprite.prototype.revive = function(health) {
  15905. if (typeof health === 'undefined') { health = 1; }
  15906. this.alive = true;
  15907. this.exists = true;
  15908. this.visible = true;
  15909. this.health = health;
  15910. if (this.events)
  15911. {
  15912. this.events.onRevived.dispatch(this);
  15913. }
  15914. return this;
  15915. };
  15916. /**
  15917. * Kills a Sprite. A killed Sprite has its alive, exists and visible properties all set to false.
  15918. * It will dispatch the onKilled event, you can listen to Sprite.events.onKilled for the signal.
  15919. * Note that killing a Sprite is a way for you to quickly recycle it in a Sprite pool, it doesn't free it up from memory.
  15920. * If you don't need this Sprite any more you should call Sprite.destroy instead.
  15921. *
  15922. * @method Phaser.Sprite#kill
  15923. * @memberof Phaser.Sprite
  15924. * @return (Phaser.Sprite) This instance.
  15925. */
  15926. Phaser.Sprite.prototype.kill = function() {
  15927. this.alive = false;
  15928. this.exists = false;
  15929. this.visible = false;
  15930. if (this.events)
  15931. {
  15932. this.events.onKilled.dispatch(this);
  15933. }
  15934. return this;
  15935. };
  15936. /**
  15937. * Destroys the Sprite. This removes it from its parent group, destroys the input, event and animation handlers if present
  15938. * and nulls its reference to game, freeing it up for garbage collection.
  15939. *
  15940. * @method Phaser.Sprite#destroy
  15941. * @memberof Phaser.Sprite
  15942. */
  15943. Phaser.Sprite.prototype.destroy = function() {
  15944. if (this.group)
  15945. {
  15946. this.group.remove(this);
  15947. }
  15948. if (this.input)
  15949. {
  15950. this.input.destroy();
  15951. }
  15952. if (this.events)
  15953. {
  15954. this.events.destroy();
  15955. }
  15956. if (this.animations)
  15957. {
  15958. this.animations.destroy();
  15959. }
  15960. this.alive = false;
  15961. this.exists = false;
  15962. this.visible = false;
  15963. this.game = null;
  15964. };
  15965. /**
  15966. * Damages the Sprite, this removes the given amount from the Sprites health property.
  15967. * If health is then taken below zero Sprite.kill is called.
  15968. *
  15969. * @method Phaser.Sprite#damage
  15970. * @memberof Phaser.Sprite
  15971. * @param {number} amount - The amount to subtract from the Sprite.health value.
  15972. * @return (Phaser.Sprite) This instance.
  15973. */
  15974. Phaser.Sprite.prototype.damage = function(amount) {
  15975. if (this.alive)
  15976. {
  15977. this.health -= amount;
  15978. if (this.health < 0)
  15979. {
  15980. this.kill();
  15981. }
  15982. }
  15983. return this;
  15984. };
  15985. /**
  15986. * Resets the Sprite. This places the Sprite at the given x/y world coordinates and then
  15987. * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values.
  15988. * If the Sprite has a physics body that too is reset.
  15989. *
  15990. * @method Phaser.Sprite#reset
  15991. * @memberof Phaser.Sprite
  15992. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  15993. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  15994. * @param {number} [health=1] - The health to give the Sprite.
  15995. * @return (Phaser.Sprite) This instance.
  15996. */
  15997. Phaser.Sprite.prototype.reset = function(x, y, health) {
  15998. if (typeof health === 'undefined') { health = 1; }
  15999. this.x = x;
  16000. this.y = y;
  16001. this.position.x = this.x;
  16002. this.position.y = this.y;
  16003. this.alive = true;
  16004. this.exists = true;
  16005. this.visible = true;
  16006. this.renderable = true;
  16007. this._outOfBoundsFired = false;
  16008. this.health = health;
  16009. if (this.body)
  16010. {
  16011. this.body.reset();
  16012. }
  16013. return this;
  16014. };
  16015. /**
  16016. * Brings the Sprite to the top of the display list it is a child of. Sprites that are members of a Phaser.Group are only
  16017. * bought to the top of that Group, not the entire display list.
  16018. *
  16019. * @method Phaser.Sprite#bringToTop
  16020. * @memberof Phaser.Sprite
  16021. * @return (Phaser.Sprite) This instance.
  16022. */
  16023. Phaser.Sprite.prototype.bringToTop = function() {
  16024. if (this.group)
  16025. {
  16026. this.group.bringToTop(this);
  16027. }
  16028. else
  16029. {
  16030. this.game.world.bringToTop(this);
  16031. }
  16032. return this;
  16033. };
  16034. /**
  16035. * Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
  16036. * If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
  16037. *
  16038. * @method Phaser.Sprite#play
  16039. * @memberof Phaser.Sprite
  16040. * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
  16041. * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
  16042. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  16043. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  16044. * @return {Phaser.Animation} A reference to playing Animation instance.
  16045. */
  16046. Phaser.Sprite.prototype.play = function (name, frameRate, loop, killOnComplete) {
  16047. if (this.animations)
  16048. {
  16049. return this.animations.play(name, frameRate, loop, killOnComplete);
  16050. }
  16051. };
  16052. /**
  16053. * Indicates the rotation of the Sprite, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  16054. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
  16055. * If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
  16056. * @name Phaser.Sprite#angle
  16057. * @property {number} angle - Gets or sets the Sprites angle of rotation in degrees.
  16058. */
  16059. Object.defineProperty(Phaser.Sprite.prototype, 'angle', {
  16060. get: function() {
  16061. return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
  16062. },
  16063. set: function(value) {
  16064. this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
  16065. }
  16066. });
  16067. /**
  16068. * @name Phaser.Sprite#frame
  16069. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  16070. */
  16071. Object.defineProperty(Phaser.Sprite.prototype, "frame", {
  16072. get: function () {
  16073. return this.animations.frame;
  16074. },
  16075. set: function (value) {
  16076. this.animations.frame = value;
  16077. }
  16078. });
  16079. /**
  16080. * @name Phaser.Sprite#frameName
  16081. * @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
  16082. */
  16083. Object.defineProperty(Phaser.Sprite.prototype, "frameName", {
  16084. get: function () {
  16085. return this.animations.frameName;
  16086. },
  16087. set: function (value) {
  16088. this.animations.frameName = value;
  16089. }
  16090. });
  16091. /**
  16092. * @name Phaser.Sprite#inCamera
  16093. * @property {boolean} inCamera - Is this sprite visible to the camera or not?
  16094. * @readonly
  16095. */
  16096. Object.defineProperty(Phaser.Sprite.prototype, "inCamera", {
  16097. get: function () {
  16098. return this._cache.cameraVisible;
  16099. }
  16100. });
  16101. /**
  16102. * The width of the sprite in pixels, setting this will actually modify the scale to acheive the value desired.
  16103. * If you wish to crop the Sprite instead see the Sprite.crop value.
  16104. *
  16105. * @name Phaser.Sprite#width
  16106. * @property {number} width - The width of the Sprite in pixels.
  16107. */
  16108. Object.defineProperty(Phaser.Sprite.prototype, 'width', {
  16109. get: function() {
  16110. return this.scale.x * this.currentFrame.width;
  16111. },
  16112. set: function(value) {
  16113. this.scale.x = value / this.currentFrame.width;
  16114. this._cache.scaleX = value / this.currentFrame.width;
  16115. this._width = value;
  16116. }
  16117. });
  16118. /**
  16119. * The height of the sprite in pixels, setting this will actually modify the scale to acheive the value desired.
  16120. * If you wish to crop the Sprite instead see the Sprite.crop value.
  16121. *
  16122. * @name Phaser.Sprite#height
  16123. * @property {number} height - The height of the Sprite in pixels.
  16124. */
  16125. Object.defineProperty(Phaser.Sprite.prototype, 'height', {
  16126. get: function() {
  16127. return this.scale.y * this.currentFrame.height;
  16128. },
  16129. set: function(value) {
  16130. this.scale.y = value / this.currentFrame.height;
  16131. this._cache.scaleY = value / this.currentFrame.height;
  16132. this._height = value;
  16133. }
  16134. });
  16135. /**
  16136. * By default a Sprite won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
  16137. * activated for this Sprite instance and it will then start to process click/touch events and more.
  16138. *
  16139. * @name Phaser.Sprite#inputEnabled
  16140. * @property {boolean} inputEnabled - Set to true to allow this Sprite to receive input events, otherwise false.
  16141. */
  16142. Object.defineProperty(Phaser.Sprite.prototype, "inputEnabled", {
  16143. get: function () {
  16144. return (this.input.enabled);
  16145. },
  16146. set: function (value) {
  16147. if (value)
  16148. {
  16149. if (this.input.enabled === false)
  16150. {
  16151. this.input.start();
  16152. }
  16153. }
  16154. else
  16155. {
  16156. if (this.input.enabled)
  16157. {
  16158. this.input.stop();
  16159. }
  16160. }
  16161. }
  16162. });
  16163. /**
  16164. * @author Richard Davey <rich@photonstorm.com>
  16165. * @copyright 2013 Photon Storm Ltd.
  16166. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  16167. */
  16168. /**
  16169. * A TileSprite is a Sprite whos texture is set to repeat and can be scrolled. As it scrolls the texture repeats (wraps) on the edges.
  16170. * @class Phaser.Tilemap
  16171. * @extends Phaser.Sprite
  16172. * @constructor
  16173. * @param {Phaser.Game} game - Current game instance.
  16174. * @param {number} x - X position of the new tileSprite.
  16175. * @param {number} y - Y position of the new tileSprite.
  16176. * @param {number} width - the width of the tilesprite.
  16177. * @param {number} height - the height of the tilesprite.
  16178. * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  16179. * @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  16180. */
  16181. Phaser.TileSprite = function (game, x, y, width, height, key, frame) {
  16182. x = x || 0;
  16183. y = y || 0;
  16184. width = width || 256;
  16185. height = height || 256;
  16186. key = key || null;
  16187. frame = frame || null;
  16188. Phaser.Sprite.call(this, game, x, y, key, frame);
  16189. /**
  16190. * @property {PIXI.Texture} texture - The texture that the sprite renders with.
  16191. */
  16192. this.texture = PIXI.TextureCache[key];
  16193. PIXI.TilingSprite.call(this, this.texture, width, height);
  16194. /**
  16195. * @property {number} type - The const type of this object.
  16196. * @readonly
  16197. */
  16198. this.type = Phaser.TILESPRITE;
  16199. /**
  16200. * @property {Phaser.Point} tileScale - The scaling of the image that is being tiled.
  16201. */
  16202. this.tileScale = new Phaser.Point(1, 1);
  16203. /**
  16204. * @property {Phaser.Point} tilePosition - The offset position of the image that is being tiled.
  16205. */
  16206. this.tilePosition = new Phaser.Point(0, 0);
  16207. };
  16208. Phaser.TileSprite.prototype = Phaser.Utils.extend(true, PIXI.TilingSprite.prototype, Phaser.Sprite.prototype);
  16209. Phaser.TileSprite.prototype.constructor = Phaser.TileSprite;
  16210. /**
  16211. * @author Richard Davey <rich@photonstorm.com>
  16212. * @copyright 2013 Photon Storm Ltd.
  16213. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  16214. */
  16215. /**
  16216. * Create a new <code>Text</code>.
  16217. * @class Phaser.Text
  16218. * @constructor
  16219. * @param {Phaser.Game} game - Current game instance.
  16220. * @param {number} x - X position of the new text object.
  16221. * @param {number} y - Y position of the new text object.
  16222. * @param {string} text - The actual text that will be written.
  16223. * @param {object} style - The style object containing style attributes like font, font size ,
  16224. */
  16225. Phaser.Text = function (game, x, y, text, style) {
  16226. x = x || 0;
  16227. y = y || 0;
  16228. text = text || '';
  16229. style = style || '';
  16230. /**
  16231. * @property {Phaser.Game} game - A reference to the currently running Game.
  16232. */
  16233. this.game = game;
  16234. /**
  16235. * @property {boolean} exists - If exists = false then the Text isn't updated by the core game loop.
  16236. * @default
  16237. */
  16238. this.exists = true;
  16239. /**
  16240. * @property {boolean} alive - This is a handy little var your game can use to determine if an object is alive or not, it doesn't effect rendering.
  16241. * @default
  16242. */
  16243. this.alive = true;
  16244. /**
  16245. * @property {Phaser.Group} group - The parent Group of this Text object.
  16246. */
  16247. this.group = null;
  16248. /**
  16249. * @property {string} name - The user defined name given to this object.
  16250. * @default
  16251. */
  16252. this.name = '';
  16253. /**
  16254. * @property {number} type - The const type of this object.
  16255. * @default
  16256. */
  16257. this.type = Phaser.TEXT;
  16258. /**
  16259. * @property {string} _text - Internal value.
  16260. * @private
  16261. */
  16262. this._text = text;
  16263. /**
  16264. * @property {string} _style - Internal value.
  16265. * @private
  16266. */
  16267. this._style = style;
  16268. PIXI.Text.call(this, text, style);
  16269. /**
  16270. * @property {Phaser.Point} position - The position of this Text object in world space.
  16271. */
  16272. this.position.x = this.x = x;
  16273. this.position.y = this.y = y;
  16274. /**
  16275. * The anchor sets the origin point of the texture.
  16276. * The default is 0,0 this means the textures origin is the top left
  16277. * Setting than anchor to 0.5,0.5 means the textures origin is centered
  16278. * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right
  16279. *
  16280. * @property {Phaser.Point} anchor - The anchor around which rotation and scaling takes place.
  16281. */
  16282. this.anchor = new Phaser.Point();
  16283. /**
  16284. * @property {Phaser.Point} scale - The scale of the object when rendered. By default it's set to 1 (no scale). You can modify it via scale.x or scale.y or scale.setTo(x, y). A value of 1 means no change to the scale, 0.5 means "half the size", 2 means "twice the size", etc.
  16285. */
  16286. this.scale = new Phaser.Point(1, 1);
  16287. /**
  16288. * @property {object} _cache - A mini cache for storing all of the calculated values.
  16289. * @private
  16290. */
  16291. this._cache = {
  16292. dirty: false,
  16293. // Transform cache
  16294. a00: 1,
  16295. a01: 0,
  16296. a02: x,
  16297. a10: 0,
  16298. a11: 1,
  16299. a12: y,
  16300. id: 1,
  16301. // The previous calculated position
  16302. x: -1,
  16303. y: -1,
  16304. // The actual scale values based on the worldTransform
  16305. scaleX: 1,
  16306. scaleY: 1
  16307. };
  16308. this._cache.x = this.x;
  16309. this._cache.y = this.y;
  16310. /**
  16311. * @property {boolean} renderable - A renderable object will be rendered to the context each frame.
  16312. */
  16313. this.renderable = true;
  16314. };
  16315. Phaser.Text.prototype = Object.create(PIXI.Text.prototype);
  16316. Phaser.Text.prototype.constructor = Phaser.Text;
  16317. /**
  16318. * Automatically called by World.update.
  16319. * @method Phaser.Text.prototype.update
  16320. */
  16321. Phaser.Text.prototype.update = function() {
  16322. if (!this.exists)
  16323. {
  16324. return;
  16325. }
  16326. this._cache.dirty = false;
  16327. this._cache.x = this.x;
  16328. this._cache.y = this.y;
  16329. if (this.position.x != this._cache.x || this.position.y != this._cache.y)
  16330. {
  16331. this.position.x = this._cache.x;
  16332. this.position.y = this._cache.y;
  16333. this._cache.dirty = true;
  16334. }
  16335. }
  16336. /**
  16337. * @method Phaser.Text.prototype.destroy
  16338. */
  16339. Phaser.Text.prototype.destroy = function() {
  16340. if (this.group)
  16341. {
  16342. this.group.remove(this);
  16343. }
  16344. if (this.canvas.parentNode)
  16345. {
  16346. this.canvas.parentNode.removeChild(this.canvas);
  16347. }
  16348. else
  16349. {
  16350. this.canvas = null;
  16351. this.context = null;
  16352. }
  16353. this.exists = false;
  16354. this.group = null;
  16355. }
  16356. /**
  16357. * Indicates the rotation of the Text, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  16358. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
  16359. * If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
  16360. * @name Phaser.Text#angle
  16361. * @property {number} angle - Gets or sets the angle of rotation in degrees.
  16362. */
  16363. Object.defineProperty(Phaser.Text.prototype, 'angle', {
  16364. get: function() {
  16365. return Phaser.Math.radToDeg(this.rotation);
  16366. },
  16367. set: function(value) {
  16368. this.rotation = Phaser.Math.degToRad(value);
  16369. }
  16370. });
  16371. /**
  16372. * The x coordinate of this object in world space.
  16373. * @name Phaser.Text#x
  16374. * @property {number} x - The x coordinate of this object in world space.
  16375. */
  16376. Object.defineProperty(Phaser.Text.prototype, 'x', {
  16377. get: function() {
  16378. return this.position.x;
  16379. },
  16380. set: function(value) {
  16381. this.position.x = value;
  16382. }
  16383. });
  16384. /**
  16385. * The y coordinate of this object in world space.
  16386. * @name Phaser.Text#y
  16387. * @property {number} y - The y coordinate of this object in world space.
  16388. */
  16389. Object.defineProperty(Phaser.Text.prototype, 'y', {
  16390. get: function() {
  16391. return this.position.y;
  16392. },
  16393. set: function(value) {
  16394. this.position.y = value;
  16395. }
  16396. });
  16397. /**
  16398. * The string to be rendered by this Text object.
  16399. * @name Phaser.Text#content
  16400. * @property {string} content - The string to be rendered by this Text object.
  16401. */
  16402. Object.defineProperty(Phaser.Text.prototype, 'content', {
  16403. get: function() {
  16404. return this._text;
  16405. },
  16406. set: function(value) {
  16407. // Let's not update unless needed, this way we can safely update the text in a core loop without constant re-draws
  16408. if (value !== this._text)
  16409. {
  16410. this._text = value;
  16411. this.setText(value);
  16412. }
  16413. }
  16414. });
  16415. /**
  16416. * The font the text will be rendered in.
  16417. * @name Phaser.Text#font
  16418. * @property {string} font - The font the text will be rendered in.
  16419. */
  16420. Object.defineProperty(Phaser.Text.prototype, 'font', {
  16421. get: function() {
  16422. return this._style;
  16423. },
  16424. set: function(value) {
  16425. // Let's not update unless needed, this way we can safely update the text in a core loop without constant re-draws
  16426. if (value !== this._style)
  16427. {
  16428. this._style = value;
  16429. this.setStyle(value);
  16430. }
  16431. }
  16432. });
  16433. /**
  16434. * @author Richard Davey <rich@photonstorm.com>
  16435. * @copyright 2013 Photon Storm Ltd.
  16436. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  16437. */
  16438. /**
  16439. * Creates a new BitmapText object.
  16440. *
  16441. * @class Phaser.BitmapText
  16442. *
  16443. * @classdesc BitmapText objects work by taking a texture file and an XML file that describes the font layout.
  16444. *
  16445. * On Windows you can use the free app BMFont: http://www.angelcode.com/products/bmfont/
  16446. *
  16447. * On OS X we recommend Glyph Designer: http://www.71squared.com/en/glyphdesigner
  16448. *
  16449. * @constructor
  16450. * @param {Phaser.Game} game - A reference to the currently running game.
  16451. * @param {number} x - X position of the new bitmapText object.
  16452. * @param {number} y - Y position of the new bitmapText object.
  16453. * @param {string} text - The actual text that will be written.
  16454. * @param {object} style - The style object containing style attributes like font, font size , etc.
  16455. */
  16456. Phaser.BitmapText = function (game, x, y, text, style) {
  16457. x = x || 0;
  16458. y = y || 0;
  16459. text = text || '';
  16460. style = style || '';
  16461. /**
  16462. * @property {Phaser.Game} game - A reference to the currently running Game.
  16463. */
  16464. this.game = game;
  16465. /**
  16466. * @property {boolean} exists - If exists = false then the Sprite isn't updated by the core game loop or physics subsystem at all.
  16467. * @default
  16468. */
  16469. this.exists = true;
  16470. /**
  16471. * @property {boolean} alive - This is a handy little var your game can use to determine if a sprite is alive or not, it doesn't effect rendering.
  16472. * @default
  16473. */
  16474. this.alive = true;
  16475. /**
  16476. * @property {Phaser.Group} group - The parent Group of this BitmapText.
  16477. */
  16478. this.group = null;
  16479. /**
  16480. * @property {string} name - The user defined name given to this BitmapText.
  16481. * @default
  16482. */
  16483. this.name = '';
  16484. /**
  16485. * @property {number} type - The const type of this object.
  16486. * @readonly
  16487. */
  16488. this.type = Phaser.BITMAPTEXT;
  16489. PIXI.BitmapText.call(this, text, style);
  16490. /**
  16491. * @property {number} position.x - The x position of this object.
  16492. */
  16493. this.position.x = x;
  16494. /**
  16495. * @property {number} position.y - The y position of this object.
  16496. */
  16497. this.position.y = y;
  16498. /**
  16499. * The anchor sets the origin point of the texture.
  16500. * The default is 0,0 this means the textures origin is the top left
  16501. * Setting than anchor to 0.5,0.5 means the textures origin is centered
  16502. * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right
  16503. *
  16504. * @property {Phaser.Point} anchor - The anchor around which rotation and scaling takes place.
  16505. */
  16506. this.anchor = new Phaser.Point();
  16507. /**
  16508. * @property {Phaser.Point} scale - The scale of the object when rendered. By default it's set to 1 (no scale). You can modify it via scale.x or scale.y or scale.setTo(x, y). A value of 1 means no change to the scale, 0.5 means "half the size", 2 means "twice the size", etc.
  16509. */
  16510. this.scale = new Phaser.Point(1, 1);
  16511. /**
  16512. * @property {object} _cache - A mini cache for storing all of the calculated values.
  16513. * @private
  16514. */
  16515. this._cache = {
  16516. dirty: false,
  16517. // Transform cache
  16518. a00: 1,
  16519. a01: 0,
  16520. a02: x,
  16521. a10: 0,
  16522. a11: 1,
  16523. a12: y,
  16524. id: 1,
  16525. // The previous calculated position
  16526. x: -1,
  16527. y: -1,
  16528. // The actual scale values based on the worldTransform
  16529. scaleX: 1,
  16530. scaleY: 1
  16531. };
  16532. this._cache.x = this.x;
  16533. this._cache.y = this.y;
  16534. /**
  16535. * @property {boolean} renderable - A renderable object will be rendered to the context each frame.
  16536. */
  16537. this.renderable = true;
  16538. };
  16539. Phaser.BitmapText.prototype = Object.create(PIXI.BitmapText.prototype);
  16540. Phaser.BitmapText.prototype.constructor = Phaser.BitmapText;
  16541. /**
  16542. * Automatically called by World.update
  16543. * @method Phaser.BitmapText.prototype.update
  16544. */
  16545. Phaser.BitmapText.prototype.update = function() {
  16546. if (!this.exists)
  16547. {
  16548. return;
  16549. }
  16550. this._cache.dirty = false;
  16551. this._cache.x = this.x;
  16552. this._cache.y = this.y;
  16553. if (this.position.x != this._cache.x || this.position.y != this._cache.y)
  16554. {
  16555. this.position.x = this._cache.x;
  16556. this.position.y = this._cache.y;
  16557. this._cache.dirty = true;
  16558. }
  16559. this.pivot.x = this.anchor.x*this.width;
  16560. this.pivot.y = this.anchor.y*this.height;
  16561. }
  16562. /**
  16563. * @method Phaser.Text.prototype.destroy
  16564. */
  16565. Phaser.BitmapText.prototype.destroy = function() {
  16566. if (this.group)
  16567. {
  16568. this.group.remove(this);
  16569. }
  16570. if (this.canvas && this.canvas.parentNode)
  16571. {
  16572. this.canvas.parentNode.removeChild(this.canvas);
  16573. }
  16574. else
  16575. {
  16576. this.canvas = null;
  16577. this.context = null;
  16578. }
  16579. this.exists = false;
  16580. this.group = null;
  16581. }
  16582. /**
  16583. * Indicates the rotation of the BitmapText, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  16584. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
  16585. * If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
  16586. * @name Phaser.BitmapText#angle
  16587. * @property {number} angle - Gets or sets the angle of rotation in degrees.
  16588. */
  16589. Object.defineProperty(Phaser.BitmapText.prototype, 'angle', {
  16590. get: function() {
  16591. return Phaser.Math.radToDeg(this.rotation);
  16592. },
  16593. set: function(value) {
  16594. this.rotation = Phaser.Math.degToRad(value);
  16595. }
  16596. });
  16597. /**
  16598. * The x coordinate of this object in world space.
  16599. * @name Phaser.BitmapText#x
  16600. * @property {number} x - The x coordinate of this object in world space.
  16601. */
  16602. Object.defineProperty(Phaser.BitmapText.prototype, 'x', {
  16603. get: function() {
  16604. return this.position.x;
  16605. },
  16606. set: function(value) {
  16607. this.position.x = value;
  16608. }
  16609. });
  16610. /**
  16611. * The y coordinate of this object in world space.
  16612. * @name Phaser.BitmapText#y
  16613. * @property {number} y - The y coordinate of this object in world space.
  16614. */
  16615. Object.defineProperty(Phaser.BitmapText.prototype, 'y', {
  16616. get: function() {
  16617. return this.position.y;
  16618. },
  16619. set: function(value) {
  16620. this.position.y = value;
  16621. }
  16622. });
  16623. /**
  16624. * @author Richard Davey <rich@photonstorm.com>
  16625. * @copyright 2013 Photon Storm Ltd.
  16626. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  16627. */
  16628. /**
  16629. * @class Phaser.Button
  16630. *
  16631. * @classdesc Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. The four states a Button responds to are:
  16632. *
  16633. * * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'.
  16634. * * 'Out' - when the Pointer that was previously over the Button moves out of it.
  16635. * * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse.
  16636. * * 'Up' - when the Pointer that was pressed down on the Button is released again.
  16637. *
  16638. * You can set a unique texture frame and Sound for any of these states.
  16639. *
  16640. * @constructor
  16641. *
  16642. * @param {Phaser.Game} game Current game instance.
  16643. * @param {number} [x] - X position of the Button.
  16644. * @param {number} [y] - Y position of the Button.
  16645. * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this Button.
  16646. * @param {function} [callback] - The function to call when this Button is pressed.
  16647. * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this').
  16648. * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
  16649. * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
  16650. * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
  16651. */
  16652. Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame) {
  16653. x = x || 0;
  16654. y = y || 0;
  16655. key = key || null;
  16656. callback = callback || null;
  16657. callbackContext = callbackContext || this;
  16658. Phaser.Sprite.call(this, game, x, y, key, outFrame);
  16659. /**
  16660. * @property {number} type - The Phaser Object Type.
  16661. */
  16662. this.type = Phaser.BUTTON;
  16663. /**
  16664. * @property {string} _onOverFrameName - Internal variable.
  16665. * @private
  16666. * @default
  16667. */
  16668. this._onOverFrameName = null;
  16669. /**
  16670. * @property {string} _onOutFrameName - Internal variable.
  16671. * @private
  16672. * @default
  16673. */
  16674. this._onOutFrameName = null;
  16675. /**
  16676. * @property {string} _onDownFrameName - Internal variable.
  16677. * @private
  16678. * @default
  16679. */
  16680. this._onDownFrameName = null;
  16681. /**
  16682. * @property {string} _onUpFrameName - Internal variable.
  16683. * @private
  16684. * @default
  16685. */
  16686. this._onUpFrameName = null;
  16687. /**
  16688. * @property {number} _onOverFrameID - Internal variable.
  16689. * @private
  16690. * @default
  16691. */
  16692. this._onOverFrameID = null;
  16693. /**
  16694. * @property {number} _onOutFrameID - Internal variable.
  16695. * @private
  16696. * @default
  16697. */
  16698. this._onOutFrameID = null;
  16699. /**
  16700. * @property {number} _onDownFrameID - Internal variable.
  16701. * @private
  16702. * @default
  16703. */
  16704. this._onDownFrameID = null;
  16705. /**
  16706. * @property {number} _onUpFrameID - Internal variable.
  16707. * @private
  16708. * @default
  16709. */
  16710. this._onUpFrameID = null;
  16711. /**
  16712. * @property {Phaser.Sound} onOverSound - The Sound to be played when this Buttons Over state is activated.
  16713. * @default
  16714. */
  16715. this.onOverSound = null;
  16716. /**
  16717. * @property {Phaser.Sound} onOutSound - The Sound to be played when this Buttons Out state is activated.
  16718. * @default
  16719. */
  16720. this.onOutSound = null;
  16721. /**
  16722. * @property {Phaser.Sound} onDownSound - The Sound to be played when this Buttons Down state is activated.
  16723. * @default
  16724. */
  16725. this.onDownSound = null;
  16726. /**
  16727. * @property {Phaser.Sound} onUpSound - The Sound to be played when this Buttons Up state is activated.
  16728. * @default
  16729. */
  16730. this.onUpSound = null;
  16731. /**
  16732. * @property {string} onOverSoundMarker - The Sound Marker used in conjunction with the onOverSound.
  16733. * @default
  16734. */
  16735. this.onOverSoundMarker = '';
  16736. /**
  16737. * @property {string} onOutSoundMarker - The Sound Marker used in conjunction with the onOutSound.
  16738. * @default
  16739. */
  16740. this.onOutSoundMarker = '';
  16741. /**
  16742. * @property {string} onDownSoundMarker - The Sound Marker used in conjunction with the onDownSound.
  16743. * @default
  16744. */
  16745. this.onDownSoundMarker = '';
  16746. /**
  16747. * @property {string} onUpSoundMarker - The Sound Marker used in conjunction with the onUpSound.
  16748. * @default
  16749. */
  16750. this.onUpSoundMarker = '';
  16751. /**
  16752. * @property {Phaser.Signal} onInputOver - The Signal (or event) dispatched when this Button is in an Over state.
  16753. */
  16754. this.onInputOver = new Phaser.Signal();
  16755. /**
  16756. * @property {Phaser.Signal} onInputOut - The Signal (or event) dispatched when this Button is in an Out state.
  16757. */
  16758. this.onInputOut = new Phaser.Signal();
  16759. /**
  16760. * @property {Phaser.Signal} onInputDown - The Signal (or event) dispatched when this Button is in an Down state.
  16761. */
  16762. this.onInputDown = new Phaser.Signal();
  16763. /**
  16764. * @property {Phaser.Signal} onInputUp - The Signal (or event) dispatched when this Button is in an Up state.
  16765. */
  16766. this.onInputUp = new Phaser.Signal();
  16767. /**
  16768. * @property {boolean} freezeFrames - When true the Button will cease to change texture frame on all events (over, out, up, down).
  16769. */
  16770. this.freezeFrames = false;
  16771. /**
  16772. * When the Button is clicked you can optionally force the state to "out".
  16773. * @property {boolean} forceOut
  16774. * @default
  16775. */
  16776. this.forceOut = true;
  16777. this.setFrames(overFrame, outFrame, downFrame);
  16778. if (callback !== null)
  16779. {
  16780. this.onInputUp.add(callback, callbackContext);
  16781. }
  16782. this.input.start(0, true);
  16783. // Redirect the input events to here so we can handle animation updates, etc
  16784. this.events.onInputOver.add(this.onInputOverHandler, this);
  16785. this.events.onInputOut.add(this.onInputOutHandler, this);
  16786. this.events.onInputDown.add(this.onInputDownHandler, this);
  16787. this.events.onInputUp.add(this.onInputUpHandler, this);
  16788. };
  16789. Phaser.Button.prototype = Object.create(Phaser.Sprite.prototype);
  16790. Phaser.Button.prototype = Phaser.Utils.extend(true, Phaser.Button.prototype, Phaser.Sprite.prototype, PIXI.Sprite.prototype);
  16791. Phaser.Button.prototype.constructor = Phaser.Button;
  16792. /**
  16793. * Used to manually set the frames that will be used for the different states of the button
  16794. * exactly like setting them in the constructor.
  16795. *
  16796. * @method Phaser.Button.prototype.setFrames
  16797. * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
  16798. * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
  16799. * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
  16800. */
  16801. Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame) {
  16802. if (overFrame !== null)
  16803. {
  16804. if (typeof overFrame === 'string')
  16805. {
  16806. this._onOverFrameName = overFrame;
  16807. if (this.input.pointerOver())
  16808. {
  16809. this.frameName = overFrame;
  16810. }
  16811. }
  16812. else
  16813. {
  16814. this._onOverFrameID = overFrame;
  16815. if (this.input.pointerOver())
  16816. {
  16817. this.frame = overFrame;
  16818. }
  16819. }
  16820. }
  16821. if (outFrame !== null)
  16822. {
  16823. if (typeof outFrame === 'string')
  16824. {
  16825. this._onOutFrameName = outFrame;
  16826. this._onUpFrameName = outFrame;
  16827. if (this.input.pointerOver() === false)
  16828. {
  16829. this.frameName = outFrame;
  16830. }
  16831. }
  16832. else
  16833. {
  16834. this._onOutFrameID = outFrame;
  16835. this._onUpFrameID = outFrame;
  16836. if (this.input.pointerOver() === false)
  16837. {
  16838. this.frame = outFrame;
  16839. }
  16840. }
  16841. }
  16842. if (downFrame !== null)
  16843. {
  16844. if (typeof downFrame === 'string')
  16845. {
  16846. this._onDownFrameName = downFrame;
  16847. if (this.input.pointerDown())
  16848. {
  16849. this.frameName = downFrame;
  16850. }
  16851. }
  16852. else
  16853. {
  16854. this._onDownFrameID = downFrame;
  16855. if (this.input.pointerDown())
  16856. {
  16857. this.frame = downFrame;
  16858. }
  16859. }
  16860. }
  16861. };
  16862. /**
  16863. * Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object.
  16864. * The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound.
  16865. * Call this function with no parameters at all to reset all sounds on this Button.
  16866. *
  16867. * @method Phaser.Button.prototype.setSounds
  16868. * @param {Phaser.Sound} [overSound] - Over Button Sound.
  16869. * @param {string} [overMarker] - Over Button Sound Marker.
  16870. * @param {Phaser.Sound} [downSound] - Down Button Sound.
  16871. * @param {string} [downMarker] - Down Button Sound Marker.
  16872. * @param {Phaser.Sound} [outSound] - Out Button Sound.
  16873. * @param {string} [outMarker] - Out Button Sound Marker.
  16874. * @param {Phaser.Sound} [upSound] - Up Button Sound.
  16875. * @param {string} [upMarker] - Up Button Sound Marker.
  16876. */
  16877. Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) {
  16878. this.setOverSound(overSound, overMarker);
  16879. this.setOutSound(outSound, outMarker);
  16880. this.setUpSound(upSound, upMarker);
  16881. this.setDownSound(downSound, downMarker);
  16882. }
  16883. /**
  16884. * The Sound to be played when a Pointer moves over this Button.
  16885. *
  16886. * @method Phaser.Button.prototype.setOverSound
  16887. * @param {Phaser.Sound} sound - The Sound that will be played.
  16888. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  16889. */
  16890. Phaser.Button.prototype.setOverSound = function (sound, marker) {
  16891. this.onOverSound = null;
  16892. this.onOverSoundMarker = '';
  16893. if (sound instanceof Phaser.Sound)
  16894. {
  16895. this.onOverSound = sound;
  16896. }
  16897. if (typeof marker === 'string')
  16898. {
  16899. this.onOverSoundMarker = marker;
  16900. }
  16901. }
  16902. /**
  16903. * The Sound to be played when a Pointer moves out of this Button.
  16904. *
  16905. * @method Phaser.Button.prototype.setOutSound
  16906. * @param {Phaser.Sound} sound - The Sound that will be played.
  16907. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  16908. */
  16909. Phaser.Button.prototype.setOutSound = function (sound, marker) {
  16910. this.onOutSound = null;
  16911. this.onOutSoundMarker = '';
  16912. if (sound instanceof Phaser.Sound)
  16913. {
  16914. this.onOutSound = sound;
  16915. }
  16916. if (typeof marker === 'string')
  16917. {
  16918. this.onOutSoundMarker = marker;
  16919. }
  16920. }
  16921. /**
  16922. * The Sound to be played when a Pointer clicks on this Button.
  16923. *
  16924. * @method Phaser.Button.prototype.setUpSound
  16925. * @param {Phaser.Sound} sound - The Sound that will be played.
  16926. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  16927. */
  16928. Phaser.Button.prototype.setUpSound = function (sound, marker) {
  16929. this.onUpSound = null;
  16930. this.onUpSoundMarker = '';
  16931. if (sound instanceof Phaser.Sound)
  16932. {
  16933. this.onUpSound = sound;
  16934. }
  16935. if (typeof marker === 'string')
  16936. {
  16937. this.onUpSoundMarker = marker;
  16938. }
  16939. }
  16940. /**
  16941. * The Sound to be played when a Pointer clicks on this Button.
  16942. *
  16943. * @method Phaser.Button.prototype.setDownSound
  16944. * @param {Phaser.Sound} sound - The Sound that will be played.
  16945. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  16946. */
  16947. Phaser.Button.prototype.setDownSound = function (sound, marker) {
  16948. this.onDownSound = null;
  16949. this.onDownSoundMarker = '';
  16950. if (sound instanceof Phaser.Sound)
  16951. {
  16952. this.onDownSound = sound;
  16953. }
  16954. if (typeof marker === 'string')
  16955. {
  16956. this.onDownSoundMarker = marker;
  16957. }
  16958. }
  16959. /**
  16960. * Internal function that handles input events.
  16961. *
  16962. * @protected
  16963. * @method Phaser.Button.prototype.onInputOverHandler
  16964. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  16965. */
  16966. Phaser.Button.prototype.onInputOverHandler = function (pointer) {
  16967. if (this.freezeFrames === false)
  16968. {
  16969. if (this._onOverFrameName != null)
  16970. {
  16971. this.frameName = this._onOverFrameName;
  16972. }
  16973. else if (this._onOverFrameID != null)
  16974. {
  16975. this.frame = this._onOverFrameID;
  16976. }
  16977. }
  16978. if (this.onOverSound)
  16979. {
  16980. this.onOverSound.play(this.onOverSoundMarker);
  16981. }
  16982. if (this.onInputOver)
  16983. {
  16984. this.onInputOver.dispatch(this, pointer);
  16985. }
  16986. };
  16987. /**
  16988. * Internal function that handles input events.
  16989. *
  16990. * @protected
  16991. * @method Phaser.Button.prototype.onInputOverHandler
  16992. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  16993. */
  16994. Phaser.Button.prototype.onInputOutHandler = function (pointer) {
  16995. if (this.freezeFrames === false)
  16996. {
  16997. if (this._onOutFrameName != null)
  16998. {
  16999. this.frameName = this._onOutFrameName;
  17000. }
  17001. else if (this._onOutFrameID != null)
  17002. {
  17003. this.frame = this._onOutFrameID;
  17004. }
  17005. }
  17006. if (this.onOutSound)
  17007. {
  17008. this.onOutSound.play(this.onOutSoundMarker);
  17009. }
  17010. if (this.onInputOut)
  17011. {
  17012. this.onInputOut.dispatch(this, pointer);
  17013. }
  17014. };
  17015. /**
  17016. * Internal function that handles input events.
  17017. *
  17018. * @protected
  17019. * @method Phaser.Button.prototype.onInputOverHandler
  17020. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  17021. */
  17022. Phaser.Button.prototype.onInputDownHandler = function (pointer) {
  17023. if (this.freezeFrames === false)
  17024. {
  17025. if (this._onDownFrameName != null)
  17026. {
  17027. this.frameName = this._onDownFrameName;
  17028. }
  17029. else if (this._onDownFrameID != null)
  17030. {
  17031. this.frame = this._onDownFrameID;
  17032. }
  17033. }
  17034. if (this.onDownSound)
  17035. {
  17036. this.onDownSound.play(this.onDownSoundMarker);
  17037. }
  17038. if (this.onInputDown)
  17039. {
  17040. this.onInputDown.dispatch(this, pointer);
  17041. }
  17042. };
  17043. /**
  17044. * Internal function that handles input events.
  17045. *
  17046. * @protected
  17047. * @method Phaser.Button.prototype.onInputOverHandler
  17048. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  17049. */
  17050. Phaser.Button.prototype.onInputUpHandler = function (pointer) {
  17051. if (this.freezeFrames === false)
  17052. {
  17053. if (this._onUpFrameName != null)
  17054. {
  17055. this.frameName = this._onUpFrameName;
  17056. }
  17057. else if (this._onUpFrameID != null)
  17058. {
  17059. this.frame = this._onUpFrameID;
  17060. }
  17061. }
  17062. if (this.onUpSound)
  17063. {
  17064. this.onUpSound.play(this.onUpSoundMarker);
  17065. }
  17066. if (this.forceOut && this.freezeFrames === false)
  17067. {
  17068. if (this._onOutFrameName != null)
  17069. {
  17070. this.frameName = this._onOutFrameName;
  17071. }
  17072. else if (this._onOutFrameID != null)
  17073. {
  17074. this.frame = this._onOutFrameID;
  17075. }
  17076. }
  17077. if (this.onInputUp)
  17078. {
  17079. this.onInputUp.dispatch(this, pointer);
  17080. }
  17081. };
  17082. /**
  17083. * @author Richard Davey <rich@photonstorm.com>
  17084. * @copyright 2013 Photon Storm Ltd.
  17085. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  17086. */
  17087. /**
  17088. * Creates a new `Graphics` object.
  17089. *
  17090. * @class Phaser.Graphics
  17091. * @constructor
  17092. *
  17093. * @param {Phaser.Game} game Current game instance.
  17094. * @param {number} x - X position of the new graphics object.
  17095. * @param {number} y - Y position of the new graphics object.
  17096. */
  17097. Phaser.Graphics = function (game, x, y) {
  17098. this.game = game;
  17099. PIXI.Graphics.call(this);
  17100. /**
  17101. * @property {number} type - The Phaser Object Type.
  17102. */
  17103. this.type = Phaser.GRAPHICS;
  17104. this.position.x = x;
  17105. this.position.y = y;
  17106. };
  17107. Phaser.Graphics.prototype = Object.create(PIXI.Graphics.prototype);
  17108. Phaser.Graphics.prototype.constructor = Phaser.Graphics;
  17109. /**
  17110. * Destroy this Graphics instance.
  17111. *
  17112. * @method Phaser.Sprite.prototype.destroy
  17113. */
  17114. Phaser.Graphics.prototype.destroy = function() {
  17115. this.clear();
  17116. if (this.group)
  17117. {
  17118. this.group.remove(this);
  17119. }
  17120. this.game = null;
  17121. }
  17122. /*
  17123. * Draws a {Phaser.Polygon} or a {PIXI.Polygon} filled
  17124. */
  17125. Phaser.Graphics.prototype.drawPolygon = function (poly) {
  17126. this.moveTo(poly.points[0].x, poly.points[0].y);
  17127. for (var i = 1; i < poly.points.length; i += 1)
  17128. {
  17129. this.lineTo(poly.points[i].x, poly.points[i].y);
  17130. }
  17131. this.lineTo(poly.points[0].x, poly.points[0].y);
  17132. }
  17133. Object.defineProperty(Phaser.Graphics.prototype, 'angle', {
  17134. get: function() {
  17135. return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
  17136. },
  17137. set: function(value) {
  17138. this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
  17139. }
  17140. });
  17141. Object.defineProperty(Phaser.Graphics.prototype, 'x', {
  17142. get: function() {
  17143. return this.position.x;
  17144. },
  17145. set: function(value) {
  17146. this.position.x = value;
  17147. }
  17148. });
  17149. Object.defineProperty(Phaser.Graphics.prototype, 'y', {
  17150. get: function() {
  17151. return this.position.y;
  17152. },
  17153. set: function(value) {
  17154. this.position.y = value;
  17155. }
  17156. });
  17157. /**
  17158. * @author Richard Davey <rich@photonstorm.com>
  17159. * @copyright 2013 Photon Storm Ltd.
  17160. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  17161. */
  17162. /**
  17163. * A RenderTexture is a special texture that allows any displayObject to be rendered to it.
  17164. * @class Phaser.RenderTexture
  17165. * @constructor
  17166. * @param {Phaser.Game} game - Current game instance.
  17167. * @param {string} key - Asset key for the render texture.
  17168. * @param {number} width - the width of the render texture.
  17169. * @param {number} height - the height of the render texture.
  17170. */
  17171. Phaser.RenderTexture = function (game, key, width, height) {
  17172. /**
  17173. * @property {Phaser.Game} game - A reference to the currently running game.
  17174. */
  17175. this.game = game;
  17176. /**
  17177. * @property {string} name - the name of the object.
  17178. */
  17179. this.name = key;
  17180. PIXI.EventTarget.call(this);
  17181. /**
  17182. * @property {number} width - the width.
  17183. */
  17184. this.width = width || 100;
  17185. /**
  17186. * @property {number} height - the height.
  17187. */
  17188. this.height = height || 100;
  17189. /**
  17190. * @property {PIXI.mat3} indetityMatrix - Matrix object.
  17191. */
  17192. this.indetityMatrix = PIXI.mat3.create();
  17193. /**
  17194. * @property {PIXI.Rectangle} frame - The frame for this texture.
  17195. */
  17196. this.frame = new PIXI.Rectangle(0, 0, this.width, this.height);
  17197. /**
  17198. * @property {number} type - Base Phaser object type.
  17199. */
  17200. this.type = Phaser.RENDERTEXTURE;
  17201. this._tempPoint = { x: 0, y: 0 };
  17202. if (PIXI.gl)
  17203. {
  17204. this.initWebGL();
  17205. }
  17206. else
  17207. {
  17208. this.initCanvas();
  17209. }
  17210. };
  17211. Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype);
  17212. Phaser.RenderTexture.prototype.constructor = PIXI.RenderTexture;
  17213. /**
  17214. * This function will draw the display object to the texture. If the display object is a Group or has children it will
  17215. * draw all children as well.
  17216. *
  17217. * @method render
  17218. * @param {DisplayObject} displayObject - The display object to render this texture on.
  17219. * @param {Phaser.Point} [position] - Where to draw the display object.
  17220. * @param {boolean} [clear=false] - If true the texture will be cleared before the displayObject is drawn.
  17221. */
  17222. Phaser.RenderTexture.prototype.render = function(displayObject, position, clear) {
  17223. if (typeof position === 'undefined') { position = false; }
  17224. if (typeof clear === 'undefined') { clear = false; }
  17225. if (displayObject instanceof Phaser.Group)
  17226. {
  17227. displayObject = displayObject._container;
  17228. }
  17229. if (PIXI.gl)
  17230. {
  17231. this.renderWebGL(displayObject, position, clear);
  17232. }
  17233. else
  17234. {
  17235. this.renderCanvas(displayObject, position, clear);
  17236. }
  17237. }
  17238. /**
  17239. * This function will draw the display object to the texture at the given x/y coordinates.
  17240. * If the display object is a Group or has children it will draw all children as well.
  17241. *
  17242. * @method renderXY
  17243. * @param {DisplayObject} displayObject - The display object to render this texture on.
  17244. * @param {number} x - The x coordinate to draw the display object at.
  17245. * @param {number} y - The y coordinate to draw the display object at.
  17246. * @param {boolean} [clear=false] - If true the texture will be cleared before the displayObject is drawn.
  17247. */
  17248. Phaser.RenderTexture.prototype.renderXY = function(displayObject, x, y, clear) {
  17249. this._tempPoint.x = x;
  17250. this._tempPoint.y = y;
  17251. this.render(displayObject, this._tempPoint, clear);
  17252. }
  17253. /**
  17254. * Initializes the webgl data for this texture
  17255. *
  17256. * @method initWebGL
  17257. * @private
  17258. */
  17259. Phaser.RenderTexture.prototype.initWebGL = function()
  17260. {
  17261. var gl = PIXI.gl;
  17262. this.glFramebuffer = gl.createFramebuffer();
  17263. gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer );
  17264. this.glFramebuffer.width = this.width;
  17265. this.glFramebuffer.height = this.height;
  17266. this.baseTexture = new PIXI.BaseTexture();
  17267. this.baseTexture.width = this.width;
  17268. this.baseTexture.height = this.height;
  17269. this.baseTexture._glTexture = gl.createTexture();
  17270. gl.bindTexture(gl.TEXTURE_2D, this.baseTexture._glTexture);
  17271. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  17272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  17273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  17274. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  17275. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  17276. this.baseTexture.isRender = true;
  17277. gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer );
  17278. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.baseTexture._glTexture, 0);
  17279. // create a projection matrix..
  17280. this.projection = new PIXI.Point(this.width/2 , -this.height/2);
  17281. // set the correct render function..
  17282. // this.render = this.renderWebGL;
  17283. }
  17284. Phaser.RenderTexture.prototype.resize = function(width, height)
  17285. {
  17286. this.width = width;
  17287. this.height = height;
  17288. if(PIXI.gl)
  17289. {
  17290. this.projection.x = this.width/2
  17291. this.projection.y = -this.height/2;
  17292. var gl = PIXI.gl;
  17293. gl.bindTexture(gl.TEXTURE_2D, this.baseTexture._glTexture);
  17294. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  17295. }
  17296. else
  17297. {
  17298. this.frame.width = this.width
  17299. this.frame.height = this.height;
  17300. this.renderer.resize(this.width, this.height);
  17301. }
  17302. }
  17303. /**
  17304. * Initializes the canvas data for this texture
  17305. *
  17306. * @method initCanvas
  17307. * @private
  17308. */
  17309. Phaser.RenderTexture.prototype.initCanvas = function()
  17310. {
  17311. this.renderer = new PIXI.CanvasRenderer(this.width, this.height, null, 0);
  17312. this.baseTexture = new PIXI.BaseTexture(this.renderer.view);
  17313. this.frame = new PIXI.Rectangle(0, 0, this.width, this.height);
  17314. // this.render = this.renderCanvas;
  17315. }
  17316. /**
  17317. * This function will draw the display object to the texture.
  17318. *
  17319. * @method renderWebGL
  17320. * @param displayObject {DisplayObject} The display object to render this texture on
  17321. * @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn
  17322. * @private
  17323. */
  17324. Phaser.RenderTexture.prototype.renderWebGL = function(displayObject, position, clear)
  17325. {
  17326. var gl = PIXI.gl;
  17327. // enable the alpha color mask..
  17328. gl.colorMask(true, true, true, true);
  17329. gl.viewport(0, 0, this.width, this.height);
  17330. gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer );
  17331. if (clear)
  17332. {
  17333. gl.clearColor(0,0,0, 0);
  17334. gl.clear(gl.COLOR_BUFFER_BIT);
  17335. }
  17336. // THIS WILL MESS WITH HIT TESTING!
  17337. var children = displayObject.children;
  17338. //TODO -? create a new one??? dont think so!
  17339. var originalWorldTransform = displayObject.worldTransform;
  17340. displayObject.worldTransform = PIXI.mat3.create();//sthis.indetityMatrix;
  17341. // modify to flip...
  17342. displayObject.worldTransform[4] = -1;
  17343. displayObject.worldTransform[5] = this.projection.y * -2;
  17344. if (position)
  17345. {
  17346. displayObject.worldTransform[2] = position.x;
  17347. displayObject.worldTransform[5] -= position.y;
  17348. }
  17349. PIXI.visibleCount++;
  17350. displayObject.vcount = PIXI.visibleCount;
  17351. for (var i = 0, j = children.length; i < j; i++)
  17352. {
  17353. children[i].updateTransform();
  17354. }
  17355. var renderGroup = displayObject.__renderGroup;
  17356. if (renderGroup)
  17357. {
  17358. if (displayObject == renderGroup.root)
  17359. {
  17360. renderGroup.render(this.projection, this.glFramebuffer);
  17361. }
  17362. else
  17363. {
  17364. renderGroup.renderSpecific(displayObject, this.projection, this.glFramebuffer);
  17365. }
  17366. }
  17367. else
  17368. {
  17369. if (!this.renderGroup)
  17370. {
  17371. this.renderGroup = new PIXI.WebGLRenderGroup(gl);
  17372. }
  17373. this.renderGroup.setRenderable(displayObject);
  17374. this.renderGroup.render(this.projection, this.glFramebuffer);
  17375. }
  17376. displayObject.worldTransform = originalWorldTransform;
  17377. }
  17378. /**
  17379. * This function will draw the display object to the texture.
  17380. *
  17381. * @method renderCanvas
  17382. * @param displayObject {DisplayObject} The display object to render this texture on
  17383. * @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn
  17384. * @private
  17385. */
  17386. Phaser.RenderTexture.prototype.renderCanvas = function(displayObject, position, clear)
  17387. {
  17388. var children = displayObject.children;
  17389. displayObject.worldTransform = PIXI.mat3.create();
  17390. if (position)
  17391. {
  17392. displayObject.worldTransform[2] = position.x;
  17393. displayObject.worldTransform[5] = position.y;
  17394. }
  17395. for (var i = 0, j = children.length; i < j; i++)
  17396. {
  17397. children[i].updateTransform();
  17398. }
  17399. if (clear)
  17400. {
  17401. this.renderer.context.clearRect(0, 0, this.width, this.height);
  17402. }
  17403. this.renderer.renderDisplayObject(displayObject);
  17404. this.renderer.context.setTransform(1, 0, 0, 1, 0, 0);
  17405. // PIXI.texturesToUpdate.push(this.baseTexture);
  17406. }
  17407. /**
  17408. * @author Richard Davey <rich@photonstorm.com>
  17409. * @copyright 2013 Photon Storm Ltd.
  17410. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  17411. */
  17412. /**
  17413. * The Canvas class handles everything related to the &lt;canvas&gt; tag as a DOM Element, like styles, offset, aspect ratio
  17414. *
  17415. * @class Phaser.Canvas
  17416. * @static
  17417. */
  17418. Phaser.Canvas = {
  17419. /**
  17420. * Creates the &lt;canvas&gt; tag
  17421. *
  17422. * @method Phaser.Canvas.create
  17423. * @param {number} width - The desired width.
  17424. * @param {number} height - The desired height.
  17425. * @return {HTMLCanvasElement} The newly created &lt;canvas&gt; tag.
  17426. */
  17427. create: function (width, height) {
  17428. width = width || 256;
  17429. height = height || 256;
  17430. var canvas = document.createElement('canvas');
  17431. canvas.width = width;
  17432. canvas.height = height;
  17433. canvas.style.display = 'block';
  17434. return canvas;
  17435. },
  17436. /**
  17437. * Get the DOM offset values of any given element
  17438. * @method Phaser.Canvas.getOffset
  17439. * @param {HTMLElement} element - The targeted element that we want to retrieve the offset.
  17440. * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset.
  17441. * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties.
  17442. */
  17443. getOffset: function (element, point) {
  17444. point = point || new Phaser.Point();
  17445. var box = element.getBoundingClientRect();
  17446. var clientTop = element.clientTop || document.body.clientTop || 0;
  17447. var clientLeft = element.clientLeft || document.body.clientLeft || 0;
  17448. var scrollTop = window.pageYOffset || element.scrollTop || document.body.scrollTop;
  17449. var scrollLeft = window.pageXOffset || element.scrollLeft || document.body.scrollLeft;
  17450. point.x = box.left + scrollLeft - clientLeft;
  17451. point.y = box.top + scrollTop - clientTop;
  17452. return point;
  17453. },
  17454. /**
  17455. * Returns the aspect ratio of the given canvas.
  17456. *
  17457. * @method Phaser.Canvas.getAspectRatio
  17458. * @param {HTMLCanvasElement} canvas - The canvas to get the aspect ratio from.
  17459. * @return {number} The ratio between canvas' width and height.
  17460. */
  17461. getAspectRatio: function (canvas) {
  17462. return canvas.width / canvas.height;
  17463. },
  17464. /**
  17465. * Sets the background color behind the canvas. This changes the canvas style property.
  17466. *
  17467. * @method Phaser.Canvas.setBackgroundColor
  17468. * @param {HTMLCanvasElement} canvas - The canvas to set the background color on.
  17469. * @param {string} [color] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color.
  17470. * @return {HTMLCanvasElement} Returns the source canvas.
  17471. */
  17472. setBackgroundColor: function (canvas, color) {
  17473. color = color || 'rgb(0,0,0)';
  17474. canvas.style.backgroundColor = color;
  17475. return canvas;
  17476. },
  17477. /**
  17478. * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions.
  17479. *
  17480. * @method Phaser.Canvas.setTouchAction
  17481. * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
  17482. * @param {String} [value] - The touch action to set. Defaults to 'none'.
  17483. * @return {HTMLCanvasElement} The source canvas.
  17484. */
  17485. setTouchAction: function (canvas, value) {
  17486. value = value || 'none';
  17487. canvas.style.msTouchAction = value;
  17488. canvas.style['ms-touch-action'] = value;
  17489. canvas.style['touch-action'] = value;
  17490. return canvas;
  17491. },
  17492. /**
  17493. * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions.
  17494. *
  17495. * @method Phaser.Canvas.setUserSelect
  17496. * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
  17497. * @param {String} [value] - The touch action to set. Defaults to 'none'.
  17498. * @return {HTMLCanvasElement} The source canvas.
  17499. */
  17500. setUserSelect: function (canvas, value) {
  17501. value = value || 'none';
  17502. canvas.style['-webkit-touch-callout'] = value;
  17503. canvas.style['-webkit-user-select'] = value;
  17504. canvas.style['-khtml-user-select'] = value;
  17505. canvas.style['-moz-user-select'] = value;
  17506. canvas.style['-ms-user-select'] = value;
  17507. canvas.style['user-select'] = value;
  17508. canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)';
  17509. return canvas;
  17510. },
  17511. /**
  17512. * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent.
  17513. * If no parent is given it will be added as a child of the document.body.
  17514. *
  17515. * @method Phaser.Canvas.addToDOM
  17516. * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
  17517. * @param {string|HTMLElement} parent - The DOM element to add the canvas to. Defaults to ''.
  17518. * @param {boolean} overflowHidden - If set to true it will add the overflow='hidden' style to the parent DOM element.
  17519. * @return {HTMLCanvasElement} Returns the source canvas.
  17520. */
  17521. addToDOM: function (canvas, parent, overflowHidden) {
  17522. var target;
  17523. if (typeof overflowHidden === 'undefined') { overflowHidden = true; }
  17524. if (parent)
  17525. {
  17526. // hopefully an element ID
  17527. if (typeof parent === 'string')
  17528. {
  17529. target = document.getElementById(parent);
  17530. }
  17531. // quick test for a HTMLelement
  17532. else if (typeof parent === 'object' && parent.nodeType === 1)
  17533. {
  17534. target = parent;
  17535. }
  17536. if (overflowHidden)
  17537. {
  17538. target.style.overflow = 'hidden';
  17539. }
  17540. }
  17541. // fallback, covers an invalid ID and a none HTMLelement object
  17542. if(!target)
  17543. {
  17544. target = document.body;
  17545. }
  17546. target.appendChild(canvas);
  17547. return canvas;
  17548. },
  17549. /**
  17550. * Sets the transform of the given canvas to the matrix values provided.
  17551. *
  17552. * @method Phaser.Canvas.setTransform
  17553. * @param {CanvasRenderingContext2D} context - The context to set the transform on.
  17554. * @param {number} translateX - The value to translate horizontally by.
  17555. * @param {number} translateY - The value to translate vertically by.
  17556. * @param {number} scaleX - The value to scale horizontally by.
  17557. * @param {number} scaleY - The value to scale vertically by.
  17558. * @param {number} skewX - The value to skew horizontaly by.
  17559. * @param {number} skewY - The value to skew vertically by.
  17560. * @return {CanvasRenderingContext2D} Returns the source context.
  17561. */
  17562. setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) {
  17563. context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY);
  17564. return context;
  17565. },
  17566. /**
  17567. * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing.
  17568. * By default browsers have image smoothing enabled, which isn't always what you visually want, especially
  17569. * when using pixel art in a game. Note that this sets the property on the context itself, so that any image
  17570. * drawn to the context will be affected. This sets the property across all current browsers but support is
  17571. * patchy on earlier browsers, especially on mobile.
  17572. *
  17573. * @method Phaser.Canvas.setSmoothingEnabled
  17574. * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on.
  17575. * @param {boolean} value - If set to true it will enable image smoothing, false will disable it.
  17576. * @return {CanvasRenderingContext2D} Returns the source context.
  17577. */
  17578. setSmoothingEnabled: function (context, value) {
  17579. context['imageSmoothingEnabled'] = value;
  17580. context['mozImageSmoothingEnabled'] = value;
  17581. context['oImageSmoothingEnabled'] = value;
  17582. context['webkitImageSmoothingEnabled'] = value;
  17583. context['msImageSmoothingEnabled'] = value;
  17584. return context;
  17585. },
  17586. /**
  17587. * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast on webkit').
  17588. * Note that if this doesn't given the desired result then see the setSmoothingEnabled.
  17589. *
  17590. * @method Phaser.Canvas.setImageRenderingCrisp
  17591. * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on.
  17592. * @return {HTMLCanvasElement} Returns the source canvas.
  17593. */
  17594. setImageRenderingCrisp: function (canvas) {
  17595. canvas.style['image-rendering'] = 'crisp-edges';
  17596. canvas.style['image-rendering'] = '-moz-crisp-edges';
  17597. canvas.style['image-rendering'] = '-webkit-optimize-contrast';
  17598. canvas.style.msInterpolationMode = 'nearest-neighbor';
  17599. return canvas;
  17600. },
  17601. /**
  17602. * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto').
  17603. * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method.
  17604. *
  17605. * @method Phaser.Canvas.setImageRenderingBicubic
  17606. * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on.
  17607. * @return {HTMLCanvasElement} Returns the source canvas.
  17608. */
  17609. setImageRenderingBicubic: function (canvas) {
  17610. canvas.style['image-rendering'] = 'auto';
  17611. canvas.style.msInterpolationMode = 'bicubic';
  17612. return canvas;
  17613. }
  17614. };
  17615. /**
  17616. * @author Richard Davey <rich@photonstorm.com>
  17617. * @copyright 2013 Photon Storm Ltd.
  17618. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  17619. */
  17620. /**
  17621. * The StageScaleMode object is responsible for helping you manage the scaling, resizing and alignment of your game within the browser.
  17622. *
  17623. * @class Phaser.StageScaleMode
  17624. * @constructor
  17625. * @param {Phaser.Game} game - A reference to the currently running game.
  17626. * @param {number} width - The native width of the game.
  17627. * @param {number} height - The native height of the game.
  17628. */
  17629. Phaser.StageScaleMode = function (game, width, height) {
  17630. /**
  17631. * @property {Phaser.Game} game - A reference to the currently running game.
  17632. */
  17633. this.game = game;
  17634. /**
  17635. * @property {number} width - Width of the stage after calculation.
  17636. */
  17637. this.width = width;
  17638. /**
  17639. * @property {number} height - Height of the stage after calculation.
  17640. */
  17641. this.height = height;
  17642. /**
  17643. * @property {number} minWidth - Minimum width the canvas should be scaled to (in pixels).
  17644. * @default
  17645. */
  17646. this.minWidth = null;
  17647. /**
  17648. * @property {number} maxWidth - Maximum width the canvas should be scaled to (in pixels).
  17649. * If null it will scale to whatever width the browser can handle.
  17650. * @default
  17651. */
  17652. this.maxWidth = null;
  17653. /**
  17654. * @property {number} minHeight - Minimum height the canvas should be scaled to (in pixels).
  17655. * @default
  17656. */
  17657. this.minHeight = null;
  17658. /**
  17659. * @property {number} maxHeight - Maximum height the canvas should be scaled to (in pixels).
  17660. * If null it will scale to whatever height the browser can handle.
  17661. * @default
  17662. */
  17663. this.maxHeight = null;
  17664. /**
  17665. * @property {number} _startHeight - Stage height when starting the game.
  17666. * @default
  17667. * @private
  17668. */
  17669. this._startHeight = 0;
  17670. /**
  17671. * @property {boolean} forceLandscape - If the game should be forced to use Landscape mode, this is set to true by Game.Stage
  17672. * @default
  17673. */
  17674. this.forceLandscape = false;
  17675. /**
  17676. * @property {boolean} forcePortrait - If the game should be forced to use Portrait mode, this is set to true by Game.Stage
  17677. * @default
  17678. */
  17679. this.forcePortrait = false;
  17680. /**
  17681. * @property {boolean} incorrectOrientation - If the game should be forced to use a specific orientation and the device currently isn't in that orientation this is set to true.
  17682. * @default
  17683. */
  17684. this.incorrectOrientation = false;
  17685. /**
  17686. * @property {boolean} pageAlignHorizontally - If you wish to align your game in the middle of the page then you can set this value to true.
  17687. * It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing.
  17688. * It doesn't care about any other DOM element that may be on the page, it literally just sets the margin.
  17689. * @default
  17690. */
  17691. this.pageAlignHorizontally = false;
  17692. /**
  17693. * @property {boolean} pageAlignVertically - If you wish to align your game in the middle of the page then you can set this value to true.
  17694. * It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing.
  17695. * It doesn't care about any other DOM element that may be on the page, it literally just sets the margin.
  17696. * @default
  17697. */
  17698. this.pageAlignVertically = false;
  17699. /**
  17700. * @property {number} _width - Cached stage width for full screen mode.
  17701. * @default
  17702. * @private
  17703. */
  17704. this._width = 0;
  17705. /**
  17706. * @property {number} _height - Cached stage height for full screen mode.
  17707. * @default
  17708. * @private
  17709. */
  17710. this._height = 0;
  17711. /**
  17712. * @property {number} maxIterations - The maximum number of times it will try to resize the canvas to fill the browser.
  17713. * @default
  17714. */
  17715. this.maxIterations = 5;
  17716. /**
  17717. * @property {PIXI.Sprite} orientationSprite - The Sprite that is optionally displayed if the browser enters an unsupported orientation.
  17718. * @default
  17719. */
  17720. this.orientationSprite = null;
  17721. /**
  17722. * @property {Phaser.Signal} enterLandscape - The event that is dispatched when the browser enters landscape orientation.
  17723. */
  17724. this.enterLandscape = new Phaser.Signal();
  17725. /**
  17726. * @property {Phaser.Signal} enterPortrait - The event that is dispatched when the browser enters horizontal orientation.
  17727. */
  17728. this.enterPortrait = new Phaser.Signal();
  17729. /**
  17730. * @property {Phaser.Signal} enterIncorrectOrientation - The event that is dispatched when the browser enters an incorrect orientation, as defined by forceOrientation.
  17731. */
  17732. this.enterIncorrectOrientation = new Phaser.Signal();
  17733. /**
  17734. * @property {Phaser.Signal} leaveIncorrectOrientation - The event that is dispatched when the browser leaves an incorrect orientation, as defined by forceOrientation.
  17735. */
  17736. this.leaveIncorrectOrientation = new Phaser.Signal();
  17737. /**
  17738. * @property {Phaser.Signal} hasResized - The event that is dispatched when the game scale changes.
  17739. */
  17740. this.hasResized = new Phaser.Signal();
  17741. if (window['orientation'])
  17742. {
  17743. this.orientation = window['orientation'];
  17744. }
  17745. else
  17746. {
  17747. if (window.outerWidth > window.outerHeight)
  17748. {
  17749. this.orientation = 90;
  17750. }
  17751. else
  17752. {
  17753. this.orientation = 0;
  17754. }
  17755. }
  17756. /**
  17757. * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions.
  17758. * @readonly
  17759. */
  17760. this.scaleFactor = new Phaser.Point(1, 1);
  17761. /**
  17762. * @property {Phaser.Point} scaleFactorInversed - The inversed scale factor. The displayed dimensions divided by the game dimensions.
  17763. * @readonly
  17764. */
  17765. this.scaleFactorInversed = new Phaser.Point(1, 1);
  17766. /**
  17767. * @property {Phaser.Point} margin - If the game canvas is seto to align by adjusting the margin, the margin calculation values are stored in this Point.
  17768. * @readonly
  17769. */
  17770. this.margin = new Phaser.Point(0, 0);
  17771. /**
  17772. * @property {number} aspectRatio - Aspect ratio.
  17773. * @default
  17774. */
  17775. this.aspectRatio = 0;
  17776. /**
  17777. * @property {any} event- The native browser events from full screen API changes.
  17778. */
  17779. this.event = null;
  17780. var _this = this;
  17781. window.addEventListener('orientationchange', function (event) {
  17782. return _this.checkOrientation(event);
  17783. }, false);
  17784. window.addEventListener('resize', function (event) {
  17785. return _this.checkResize(event);
  17786. }, false);
  17787. document.addEventListener('webkitfullscreenchange', function (event) {
  17788. return _this.fullScreenChange(event);
  17789. }, false);
  17790. document.addEventListener('mozfullscreenchange', function (event) {
  17791. return _this.fullScreenChange(event);
  17792. }, false);
  17793. document.addEventListener('fullscreenchange', function (event) {
  17794. return _this.fullScreenChange(event);
  17795. }, false);
  17796. };
  17797. /**
  17798. * @constant
  17799. * @type {number}
  17800. */
  17801. Phaser.StageScaleMode.EXACT_FIT = 0;
  17802. /**
  17803. * @constant
  17804. * @type {number}
  17805. */
  17806. Phaser.StageScaleMode.NO_SCALE = 1;
  17807. /**
  17808. * @constant
  17809. * @type {number}
  17810. */
  17811. Phaser.StageScaleMode.SHOW_ALL = 2;
  17812. Phaser.StageScaleMode.prototype = {
  17813. /**
  17814. * Tries to enter the browser into full screen mode.
  17815. * Please note that this needs to be supported by the web browser and isn't the same thing as setting your game to fill the browser.
  17816. * @method Phaser.StageScaleMode#startFullScreen
  17817. * @param {boolean} antialias - You can toggle the anti-alias feature of the canvas before jumping in to full screen (false = retain pixel art, true = smooth art)
  17818. */
  17819. startFullScreen: function (antialias) {
  17820. if (this.isFullScreen)
  17821. {
  17822. return;
  17823. }
  17824. if (typeof antialias !== 'undefined')
  17825. {
  17826. Phaser.Canvas.setSmoothingEnabled(this.game.context, antialias);
  17827. }
  17828. var element = this.game.canvas;
  17829. this._width = this.width;
  17830. this._height = this.height;
  17831. console.log('startFullScreen', this._width, this._height);
  17832. if (element['requestFullScreen'])
  17833. {
  17834. element['requestFullScreen']();
  17835. }
  17836. else if (element['mozRequestFullScreen'])
  17837. {
  17838. element['mozRequestFullScreen']();
  17839. }
  17840. else if (element['webkitRequestFullScreen'])
  17841. {
  17842. element['webkitRequestFullScreen'](Element.ALLOW_KEYBOARD_INPUT);
  17843. }
  17844. },
  17845. /**
  17846. * Stops full screen mode if the browser is in it.
  17847. * @method Phaser.StageScaleMode#stopFullScreen
  17848. */
  17849. stopFullScreen: function () {
  17850. if (document['cancelFullScreen'])
  17851. {
  17852. document['cancelFullScreen']();
  17853. }
  17854. else if (document['mozCancelFullScreen'])
  17855. {
  17856. document['mozCancelFullScreen']();
  17857. }
  17858. else if (document['webkitCancelFullScreen'])
  17859. {
  17860. document['webkitCancelFullScreen']();
  17861. }
  17862. },
  17863. /**
  17864. * Called automatically when the browser enters of leaves full screen mode.
  17865. * @method Phaser.StageScaleMode#fullScreenChange
  17866. * @param {Event} event - The fullscreenchange event
  17867. * @protected
  17868. */
  17869. fullScreenChange: function (event) {
  17870. this.event = event;
  17871. if (this.isFullScreen)
  17872. {
  17873. this.game.stage.canvas.style['width'] = '100%';
  17874. this.game.stage.canvas.style['height'] = '100%';
  17875. this.setMaximum();
  17876. this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
  17877. this.aspectRatio = this.width / this.height;
  17878. this.scaleFactor.x = this.game.width / this.width;
  17879. this.scaleFactor.y = this.game.height / this.height;
  17880. }
  17881. else
  17882. {
  17883. this.game.stage.canvas.style['width'] = this.game.width + 'px';
  17884. this.game.stage.canvas.style['height'] = this.game.height + 'px';
  17885. this.width = this._width;
  17886. this.height = this._height;
  17887. this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
  17888. this.aspectRatio = this.width / this.height;
  17889. this.scaleFactor.x = this.game.width / this.width;
  17890. this.scaleFactor.y = this.game.height / this.height;
  17891. }
  17892. },
  17893. /**
  17894. * If you need your game to run in only one orientation you can force that to happen.
  17895. * The optional orientationImage is displayed when the game is in the incorrect orientation.
  17896. * @method Phaser.StageScaleMode#forceOrientation
  17897. * @param {boolean} forceLandscape - true if the game should run in landscape mode only.
  17898. * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only.
  17899. * @param {string} [orientationImage=''] - The string of an image in the Phaser.Cache to display when this game is in the incorrect orientation.
  17900. */
  17901. forceOrientation: function (forceLandscape, forcePortrait, orientationImage) {
  17902. if (typeof forcePortrait === 'undefined') { forcePortrait = false; }
  17903. this.forceLandscape = forceLandscape;
  17904. this.forcePortrait = forcePortrait;
  17905. if (typeof orientationImage !== 'undefined')
  17906. {
  17907. if (orientationImage == null || this.game.cache.checkImageKey(orientationImage) === false)
  17908. {
  17909. orientationImage = '__default';
  17910. }
  17911. this.orientationSprite = new PIXI.Sprite(PIXI.TextureCache[orientationImage]);
  17912. this.orientationSprite.anchor.x = 0.5;
  17913. this.orientationSprite.anchor.y = 0.5;
  17914. this.orientationSprite.position.x = this.game.width / 2;
  17915. this.orientationSprite.position.y = this.game.height / 2;
  17916. this.checkOrientationState();
  17917. if (this.incorrectOrientation)
  17918. {
  17919. this.orientationSprite.visible = true;
  17920. this.game.world.visible = false;
  17921. }
  17922. else
  17923. {
  17924. this.orientationSprite.visible = false;
  17925. this.game.world.visible = true;
  17926. }
  17927. this.game.stage._stage.addChild(this.orientationSprite);
  17928. }
  17929. },
  17930. /**
  17931. * Checks if the browser is in the correct orientation for your game (if forceLandscape or forcePortrait have been set)
  17932. * @method Phaser.StageScaleMode#checkOrientationState
  17933. */
  17934. checkOrientationState: function () {
  17935. // They are in the wrong orientation
  17936. if (this.incorrectOrientation)
  17937. {
  17938. if ((this.forceLandscape && window.innerWidth > window.innerHeight) || (this.forcePortrait && window.innerHeight > window.innerWidth))
  17939. {
  17940. // Back to normal
  17941. this.game.paused = false;
  17942. this.incorrectOrientation = false;
  17943. this.leaveIncorrectOrientation.dispatch();
  17944. if (this.orientationSprite)
  17945. {
  17946. this.orientationSprite.visible = false;
  17947. this.game.world.visible = true;
  17948. }
  17949. this.refresh();
  17950. }
  17951. }
  17952. else
  17953. {
  17954. if ((this.forceLandscape && window.innerWidth < window.innerHeight) || (this.forcePortrait && window.innerHeight < window.innerWidth))
  17955. {
  17956. // Show orientation screen
  17957. this.game.paused = true;
  17958. this.incorrectOrientation = true;
  17959. this.enterIncorrectOrientation.dispatch();
  17960. if (this.orientationSprite && this.orientationSprite.visible === false)
  17961. {
  17962. this.orientationSprite.visible = true;
  17963. this.game.world.visible = false;
  17964. }
  17965. this.refresh();
  17966. }
  17967. }
  17968. },
  17969. /**
  17970. * Handle window.orientationchange events
  17971. * @method Phaser.StageScaleMode#checkOrientation
  17972. * @param {Event} event - The orientationchange event data.
  17973. */
  17974. checkOrientation: function (event) {
  17975. this.event = event;
  17976. this.orientation = window['orientation'];
  17977. if (this.isLandscape)
  17978. {
  17979. this.enterLandscape.dispatch(this.orientation, true, false);
  17980. }
  17981. else
  17982. {
  17983. this.enterPortrait.dispatch(this.orientation, false, true);
  17984. }
  17985. if (this.game.stage.scaleMode !== Phaser.StageScaleMode.NO_SCALE)
  17986. {
  17987. this.refresh();
  17988. }
  17989. },
  17990. /**
  17991. * Handle window.resize events
  17992. * @method Phaser.StageScaleMode#checkResize
  17993. * @param {Event} event - The resize event data.
  17994. */
  17995. checkResize: function (event) {
  17996. this.event = event;
  17997. if (window.outerWidth > window.outerHeight)
  17998. {
  17999. this.orientation = 90;
  18000. }
  18001. else
  18002. {
  18003. this.orientation = 0;
  18004. }
  18005. if (this.isLandscape)
  18006. {
  18007. this.enterLandscape.dispatch(this.orientation, true, false);
  18008. }
  18009. else
  18010. {
  18011. this.enterPortrait.dispatch(this.orientation, false, true);
  18012. }
  18013. if (this.game.stage.scaleMode !== Phaser.StageScaleMode.NO_SCALE)
  18014. {
  18015. this.refresh();
  18016. }
  18017. this.checkOrientationState();
  18018. },
  18019. /**
  18020. * Re-calculate scale mode and update screen size.
  18021. * @method Phaser.StageScaleMode#refresh
  18022. */
  18023. refresh: function () {
  18024. // We can't do anything about the status bars in iPads, web apps or desktops
  18025. if (this.game.device.iPad === false && this.game.device.webApp === false && this.game.device.desktop === false)
  18026. {
  18027. if (this.game.device.android && this.game.device.chrome === false)
  18028. {
  18029. window.scrollTo(0, 1);
  18030. }
  18031. else
  18032. {
  18033. window.scrollTo(0, 0);
  18034. }
  18035. }
  18036. if (this._check == null && this.maxIterations > 0)
  18037. {
  18038. this._iterations = this.maxIterations;
  18039. var _this = this;
  18040. this._check = window.setInterval(function () {
  18041. return _this.setScreenSize();
  18042. }, 10);
  18043. this.setScreenSize();
  18044. }
  18045. },
  18046. /**
  18047. * Set screen size automatically based on the scaleMode.
  18048. * @param {boolean} force - If force is true it will try to resize the game regardless of the document dimensions.
  18049. */
  18050. setScreenSize: function (force) {
  18051. if (typeof force == 'undefined')
  18052. {
  18053. force = false;
  18054. }
  18055. if (this.game.device.iPad === false && this.game.device.webApp === false && this.game.device.desktop === false)
  18056. {
  18057. if (this.game.device.android && this.game.device.chrome === false)
  18058. {
  18059. window.scrollTo(0, 1);
  18060. }
  18061. else
  18062. {
  18063. window.scrollTo(0, 0);
  18064. }
  18065. }
  18066. this._iterations--;
  18067. if (force || window.innerHeight > this._startHeight || this._iterations < 0)
  18068. {
  18069. // Set minimum height of content to new window height
  18070. document.documentElement['style'].minHeight = window.innerHeight + 'px';
  18071. if (this.incorrectOrientation === true)
  18072. {
  18073. this.setMaximum();
  18074. }
  18075. else if (this.game.stage.scaleMode == Phaser.StageScaleMode.EXACT_FIT)
  18076. {
  18077. this.setExactFit();
  18078. }
  18079. else if (this.game.stage.scaleMode == Phaser.StageScaleMode.SHOW_ALL)
  18080. {
  18081. this.setShowAll();
  18082. }
  18083. this.setSize();
  18084. clearInterval(this._check);
  18085. this._check = null;
  18086. }
  18087. },
  18088. /**
  18089. * Sets the canvas style width and height values based on minWidth/Height and maxWidth/Height.
  18090. * @method Phaser.StageScaleMode#setSize
  18091. */
  18092. setSize: function () {
  18093. if (this.incorrectOrientation === false)
  18094. {
  18095. if (this.maxWidth && this.width > this.maxWidth)
  18096. {
  18097. this.width = this.maxWidth;
  18098. }
  18099. if (this.maxHeight && this.height > this.maxHeight)
  18100. {
  18101. this.height = this.maxHeight;
  18102. }
  18103. if (this.minWidth && this.width < this.minWidth)
  18104. {
  18105. this.width = this.minWidth;
  18106. }
  18107. if (this.minHeight && this.height < this.minHeight)
  18108. {
  18109. this.height = this.minHeight;
  18110. }
  18111. }
  18112. this.game.canvas.style.width = this.width + 'px';
  18113. this.game.canvas.style.height = this.height + 'px';
  18114. this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
  18115. if (this.pageAlignHorizontally)
  18116. {
  18117. if (this.width < window.innerWidth && this.incorrectOrientation === false)
  18118. {
  18119. this.margin.x = Math.round((window.innerWidth - this.width) / 2);
  18120. this.game.canvas.style.marginLeft = this.margin.x + 'px';
  18121. }
  18122. else
  18123. {
  18124. this.margin.x = 0;
  18125. this.game.canvas.style.marginLeft = '0px';
  18126. }
  18127. }
  18128. if (this.pageAlignVertically)
  18129. {
  18130. if (this.height < window.innerHeight && this.incorrectOrientation === false)
  18131. {
  18132. this.margin.y = Math.round((window.innerHeight - this.height) / 2);
  18133. this.game.canvas.style.marginTop = this.margin.y + 'px';
  18134. }
  18135. else
  18136. {
  18137. this.margin.y = 0;
  18138. this.game.canvas.style.marginTop = '0px';
  18139. }
  18140. }
  18141. Phaser.Canvas.getOffset(this.game.canvas, this.game.stage.offset);
  18142. this.aspectRatio = this.width / this.height;
  18143. this.scaleFactor.x = this.game.width / this.width;
  18144. this.scaleFactor.y = this.game.height / this.height;
  18145. this.scaleFactorInversed.x = this.width / this.game.width;
  18146. this.scaleFactorInversed.y = this.height / this.game.height;
  18147. this.hasResized.dispatch(this.width, this.height);
  18148. this.checkOrientationState();
  18149. },
  18150. /**
  18151. * Sets this.width equal to window.innerWidth and this.height equal to window.innerHeight
  18152. * @method Phaser.StageScaleMode#setMaximum
  18153. */
  18154. setMaximum: function () {
  18155. this.width = window.innerWidth;
  18156. this.height = window.innerHeight;
  18157. },
  18158. /**
  18159. * Calculates the multiplier needed to scale the game proportionally.
  18160. * @method Phaser.StageScaleMode#setShowAll
  18161. */
  18162. setShowAll: function () {
  18163. var multiplier = Math.min((window.innerHeight / this.game.height), (window.innerWidth / this.game.width));
  18164. this.width = Math.round(this.game.width * multiplier);
  18165. this.height = Math.round(this.game.height * multiplier);
  18166. },
  18167. /**
  18168. * Sets the width and height values of the canvas, no larger than the maxWidth/Height.
  18169. * @method Phaser.StageScaleMode#setExactFit
  18170. */
  18171. setExactFit: function () {
  18172. var availableWidth = window.innerWidth;
  18173. var availableHeight = window.innerHeight;
  18174. // console.log('available', availableWidth, availableHeight);
  18175. if (this.maxWidth && availableWidth > this.maxWidth)
  18176. {
  18177. this.width = this.maxWidth;
  18178. }
  18179. else
  18180. {
  18181. this.width = availableWidth;
  18182. }
  18183. if (this.maxHeight && availableHeight > this.maxHeight)
  18184. {
  18185. this.height = this.maxHeight;
  18186. }
  18187. else
  18188. {
  18189. this.height = availableHeight;
  18190. }
  18191. }
  18192. };
  18193. /**
  18194. * @name Phaser.StageScaleMode#isFullScreen
  18195. * @property {boolean} isFullScreen - Returns true if the browser is in full screen mode, otherwise false.
  18196. * @readonly
  18197. */
  18198. Object.defineProperty(Phaser.StageScaleMode.prototype, "isFullScreen", {
  18199. get: function () {
  18200. return (document['fullscreenElement'] || document['mozFullScreenElement'] || document['webkitFullscreenElement'])
  18201. }
  18202. });
  18203. /**
  18204. * @name Phaser.StageScaleMode#isPortrait
  18205. * @property {boolean} isPortrait - Returns true if the browser dimensions match a portrait display.
  18206. * @readonly
  18207. */
  18208. Object.defineProperty(Phaser.StageScaleMode.prototype, "isPortrait", {
  18209. get: function () {
  18210. return this.orientation === 0 || this.orientation == 180;
  18211. }
  18212. });
  18213. /**
  18214. * @name Phaser.StageScaleMode#isLandscape
  18215. * @property {boolean} isLandscape - Returns true if the browser dimensions match a landscape display.
  18216. * @readonly
  18217. */
  18218. Object.defineProperty(Phaser.StageScaleMode.prototype, "isLandscape", {
  18219. get: function () {
  18220. return this.orientation === 90 || this.orientation === -90;
  18221. }
  18222. });
  18223. /**
  18224. * @author Richard Davey <rich@photonstorm.com>
  18225. * @copyright 2013 Photon Storm Ltd.
  18226. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  18227. */
  18228. /**
  18229. * Detects device support capabilities. Using some elements from System.js by MrDoob and Modernizr
  18230. *
  18231. * @class Phaser.Device
  18232. * @constructor
  18233. */
  18234. Phaser.Device = function () {
  18235. /**
  18236. * An optional 'fix' for the horrendous Android stock browser bug https://code.google.com/p/android/issues/detail?id=39247
  18237. * @property {boolean} patchAndroidClearRectBug - Description.
  18238. * @default
  18239. */
  18240. this.patchAndroidClearRectBug = false;
  18241. // Operating System
  18242. /**
  18243. * @property {boolean} desktop - Is running desktop?
  18244. * @default
  18245. */
  18246. this.desktop = false;
  18247. /**
  18248. * @property {boolean} iOS - Is running on iOS?
  18249. * @default
  18250. */
  18251. this.iOS = false;
  18252. /**
  18253. * @property {boolean} cocoonJS - Is the game running under CocoonJS?
  18254. * @default
  18255. */
  18256. this.cocoonJS = false;
  18257. /**
  18258. * @property {boolean} android - Is running on android?
  18259. * @default
  18260. */
  18261. this.android = false;
  18262. /**
  18263. * @property {boolean} chromeOS - Is running on chromeOS?
  18264. * @default
  18265. */
  18266. this.chromeOS = false;
  18267. /**
  18268. * @property {boolean} linux - Is running on linux?
  18269. * @default
  18270. */
  18271. this.linux = false;
  18272. /**
  18273. * @property {boolean} macOS - Is running on macOS?
  18274. * @default
  18275. */
  18276. this.macOS = false;
  18277. /**
  18278. * @property {boolean} windows - Is running on windows?
  18279. * @default
  18280. */
  18281. this.windows = false;
  18282. // Features
  18283. /**
  18284. * @property {boolean} canvas - Is canvas available?
  18285. * @default
  18286. */
  18287. this.canvas = false;
  18288. /**
  18289. * @property {boolean} file - Is file available?
  18290. * @default
  18291. */
  18292. this.file = false;
  18293. /**
  18294. * @property {boolean} fileSystem - Is fileSystem available?
  18295. * @default
  18296. */
  18297. this.fileSystem = false;
  18298. /**
  18299. * @property {boolean} localStorage - Is localStorage available?
  18300. * @default
  18301. */
  18302. this.localStorage = false;
  18303. /**
  18304. * @property {boolean} webGL - Is webGL available?
  18305. * @default
  18306. */
  18307. this.webGL = false;
  18308. /**
  18309. * @property {boolean} worker - Is worker available?
  18310. * @default
  18311. */
  18312. this.worker = false;
  18313. /**
  18314. * @property {boolean} touch - Is touch available?
  18315. * @default
  18316. */
  18317. this.touch = false;
  18318. /**
  18319. * @property {boolean} mspointer - Is mspointer available?
  18320. * @default
  18321. */
  18322. this.mspointer = false;
  18323. /**
  18324. * @property {boolean} css3D - Is css3D available?
  18325. * @default
  18326. */
  18327. this.css3D = false;
  18328. /**
  18329. * @property {boolean} pointerLock - Is Pointer Lock available?
  18330. * @default
  18331. */
  18332. this.pointerLock = false;
  18333. /**
  18334. * @property {boolean} typedArray - Does the browser support TypedArrays?
  18335. * @default
  18336. */
  18337. this.typedArray = false;
  18338. // Browser
  18339. /**
  18340. * @property {boolean} arora - Set to true if running in Arora.
  18341. * @default
  18342. */
  18343. this.arora = false;
  18344. /**
  18345. * @property {boolean} chrome - Set to true if running in Chrome.
  18346. * @default
  18347. */
  18348. this.chrome = false;
  18349. /**
  18350. * @property {boolean} epiphany - Set to true if running in Epiphany.
  18351. * @default
  18352. */
  18353. this.epiphany = false;
  18354. /**
  18355. * @property {boolean} firefox - Set to true if running in Firefox.
  18356. * @default
  18357. */
  18358. this.firefox = false;
  18359. /**
  18360. * @property {boolean} ie - Set to true if running in Internet Explorer.
  18361. * @default
  18362. */
  18363. this.ie = false;
  18364. /**
  18365. * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number.
  18366. * @default
  18367. */
  18368. this.ieVersion = 0;
  18369. /**
  18370. * @property {boolean} mobileSafari - Set to true if running in Mobile Safari.
  18371. * @default
  18372. */
  18373. this.mobileSafari = false;
  18374. /**
  18375. * @property {boolean} midori - Set to true if running in Midori.
  18376. * @default
  18377. */
  18378. this.midori = false;
  18379. /**
  18380. * @property {boolean} opera - Set to true if running in Opera.
  18381. * @default
  18382. */
  18383. this.opera = false;
  18384. /**
  18385. * @property {boolean} safari - Set to true if running in Safari.
  18386. * @default
  18387. */
  18388. this.safari = false;
  18389. /**
  18390. * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView
  18391. * @default
  18392. */
  18393. this.webApp = false;
  18394. // Audio
  18395. /**
  18396. * @property {boolean} audioData - Are Audio tags available?
  18397. * @default
  18398. */
  18399. this.audioData = false;
  18400. /**
  18401. * @property {boolean} webAudio - Is the WebAudio API available?
  18402. * @default
  18403. */
  18404. this.webAudio = false;
  18405. /**
  18406. * @property {boolean} ogg - Can this device play ogg files?
  18407. * @default
  18408. */
  18409. this.ogg = false;
  18410. /**
  18411. * @property {boolean} opus - Can this device play opus files?
  18412. * @default
  18413. */
  18414. this.opus = false;
  18415. /**
  18416. * @property {boolean} mp3 - Can this device play mp3 files?
  18417. * @default
  18418. */
  18419. this.mp3 = false;
  18420. /**
  18421. * @property {boolean} wav - Can this device play wav files?
  18422. * @default
  18423. */
  18424. this.wav = false;
  18425. /**
  18426. * Can this device play m4a files?
  18427. * @property {boolean} m4a - True if this device can play m4a files.
  18428. * @default
  18429. */
  18430. this.m4a = false;
  18431. /**
  18432. * @property {boolean} webm - Can this device play webm files?
  18433. * @default
  18434. */
  18435. this.webm = false;
  18436. // Device
  18437. /**
  18438. * @property {boolean} iPhone - Is running on iPhone?
  18439. * @default
  18440. */
  18441. this.iPhone = false;
  18442. /**
  18443. * @property {boolean} iPhone4 - Is running on iPhone4?
  18444. * @default
  18445. */
  18446. this.iPhone4 = false;
  18447. /**
  18448. * @property {boolean} iPad - Is running on iPad?
  18449. * @default
  18450. */
  18451. this.iPad = false;
  18452. /**
  18453. * @property {number} pixelRatio - PixelRatio of the host device?
  18454. * @default
  18455. */
  18456. this.pixelRatio = 0;
  18457. /**
  18458. * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays)
  18459. * @default
  18460. */
  18461. this.littleEndian = false;
  18462. // Run the checks
  18463. this._checkAudio();
  18464. this._checkBrowser();
  18465. this._checkCSS3D();
  18466. this._checkDevice();
  18467. this._checkFeatures();
  18468. this._checkOS();
  18469. };
  18470. Phaser.Device.prototype = {
  18471. /**
  18472. * Check which OS is game running on.
  18473. * @method Phaser.Device#_checkOS
  18474. * @private
  18475. */
  18476. _checkOS: function () {
  18477. var ua = navigator.userAgent;
  18478. if (/Android/.test(ua)) {
  18479. this.android = true;
  18480. } else if (/CrOS/.test(ua)) {
  18481. this.chromeOS = true;
  18482. } else if (/iP[ao]d|iPhone/i.test(ua)) {
  18483. this.iOS = true;
  18484. } else if (/Linux/.test(ua)) {
  18485. this.linux = true;
  18486. } else if (/Mac OS/.test(ua)) {
  18487. this.macOS = true;
  18488. } else if (/Windows/.test(ua)) {
  18489. this.windows = true;
  18490. }
  18491. if (this.windows || this.macOS || this.linux) {
  18492. this.desktop = true;
  18493. }
  18494. },
  18495. /**
  18496. * Check HTML5 features of the host environment.
  18497. * @method Phaser.Device#_checkFeatures
  18498. * @private
  18499. */
  18500. _checkFeatures: function () {
  18501. this.canvas = !!window['CanvasRenderingContext2D'];
  18502. try {
  18503. this.localStorage = !!localStorage.getItem;
  18504. } catch (error) {
  18505. this.localStorage = false;
  18506. }
  18507. this.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob'];
  18508. this.fileSystem = !!window['requestFileSystem'];
  18509. this.webGL = ( function () { try { var canvas = document.createElement( 'canvas' ); return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } } )();
  18510. if (this.webGL === null || this.webGL === false)
  18511. {
  18512. this.webGL = false;
  18513. }
  18514. else
  18515. {
  18516. this.webGL = true;
  18517. }
  18518. this.worker = !!window['Worker'];
  18519. if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints > 1)) {
  18520. this.touch = true;
  18521. }
  18522. if (window.navigator.msPointerEnabled || window.navigator.pointerEnabled) {
  18523. this.mspointer = true;
  18524. }
  18525. this.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
  18526. },
  18527. /**
  18528. * Check what browser is game running in.
  18529. * @method Phaser.Device#_checkBrowser
  18530. * @private
  18531. */
  18532. _checkBrowser: function () {
  18533. var ua = navigator.userAgent;
  18534. if (/Arora/.test(ua)) {
  18535. this.arora = true;
  18536. } else if (/Chrome/.test(ua)) {
  18537. this.chrome = true;
  18538. } else if (/Epiphany/.test(ua)) {
  18539. this.epiphany = true;
  18540. } else if (/Firefox/.test(ua)) {
  18541. this.firefox = true;
  18542. } else if (/Mobile Safari/.test(ua)) {
  18543. this.mobileSafari = true;
  18544. } else if (/MSIE (\d+\.\d+);/.test(ua)) {
  18545. this.ie = true;
  18546. this.ieVersion = parseInt(RegExp.$1, 10);
  18547. } else if (/Midori/.test(ua)) {
  18548. this.midori = true;
  18549. } else if (/Opera/.test(ua)) {
  18550. this.opera = true;
  18551. } else if (/Safari/.test(ua)) {
  18552. this.safari = true;
  18553. }
  18554. // WebApp mode in iOS
  18555. if (navigator['standalone']) {
  18556. this.webApp = true;
  18557. }
  18558. if (navigator['isCocoonJS']) {
  18559. this.cocoonJS = true;
  18560. }
  18561. },
  18562. /**
  18563. * Check audio support.
  18564. * @method Phaser.Device#_checkAudio
  18565. * @private
  18566. */
  18567. _checkAudio: function () {
  18568. this.audioData = !!(window['Audio']);
  18569. this.webAudio = !!(window['webkitAudioContext'] || window['AudioContext']);
  18570. var audioElement = document.createElement('audio');
  18571. var result = false;
  18572. try {
  18573. if (result = !!audioElement.canPlayType) {
  18574. if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  18575. this.ogg = true;
  18576. }
  18577. if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '')) {
  18578. this.opus = true;
  18579. }
  18580. if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) {
  18581. this.mp3 = true;
  18582. }
  18583. // Mimetypes accepted:
  18584. // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
  18585. // bit.ly/iphoneoscodecs
  18586. if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) {
  18587. this.wav = true;
  18588. }
  18589. if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) {
  18590. this.m4a = true;
  18591. }
  18592. if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) {
  18593. this.webm = true;
  18594. }
  18595. }
  18596. } catch (e) {
  18597. }
  18598. },
  18599. /**
  18600. * Check PixelRatio of devices.
  18601. * @method Phaser.Device#_checkDevice
  18602. * @private
  18603. */
  18604. _checkDevice: function () {
  18605. this.pixelRatio = window['devicePixelRatio'] || 1;
  18606. this.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') != -1;
  18607. this.iPhone4 = (this.pixelRatio == 2 && this.iPhone);
  18608. this.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') != -1;
  18609. if (typeof Int8Array !== 'undefined')
  18610. {
  18611. this.littleEndian = new Int8Array(new Int16Array([1]).buffer)[0] > 0;
  18612. this.typedArray = true;
  18613. }
  18614. else
  18615. {
  18616. this.littleEndian = false;
  18617. this.typedArray = false;
  18618. }
  18619. },
  18620. /**
  18621. * Check whether the host environment support 3D CSS.
  18622. * @method Phaser.Device#_checkCSS3D
  18623. * @private
  18624. */
  18625. _checkCSS3D: function () {
  18626. var el = document.createElement('p');
  18627. var has3d;
  18628. var transforms = {
  18629. 'webkitTransform': '-webkit-transform',
  18630. 'OTransform': '-o-transform',
  18631. 'msTransform': '-ms-transform',
  18632. 'MozTransform': '-moz-transform',
  18633. 'transform': 'transform'
  18634. };
  18635. // Add it to the body to get the computed style.
  18636. document.body.insertBefore(el, null);
  18637. for (var t in transforms) {
  18638. if (el.style[t] !== undefined) {
  18639. el.style[t] = "translate3d(1px,1px,1px)";
  18640. has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
  18641. }
  18642. }
  18643. document.body.removeChild(el);
  18644. this.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none");
  18645. },
  18646. /**
  18647. * Check whether the host environment can play audio.
  18648. * @method Phaser.Device#canPlayAudio
  18649. * @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm'.
  18650. * @return {boolean} True if the given file type is supported by the browser, otherwise false.
  18651. */
  18652. canPlayAudio: function (type) {
  18653. if (type == 'mp3' && this.mp3)
  18654. {
  18655. return true;
  18656. }
  18657. else if (type == 'ogg' && (this.ogg || this.opus))
  18658. {
  18659. return true;
  18660. }
  18661. else if (type == 'm4a' && this.m4a)
  18662. {
  18663. return true;
  18664. }
  18665. else if (type == 'wav' && this.wav)
  18666. {
  18667. return true;
  18668. }
  18669. else if (type == 'webm' && this.webm)
  18670. {
  18671. return true;
  18672. }
  18673. return false;
  18674. },
  18675. /**
  18676. * Check whether the console is open.
  18677. * @method Phaser.Device#isConsoleOpen
  18678. * @return {boolean} True if the browser dev console is open.
  18679. */
  18680. isConsoleOpen: function () {
  18681. if (window.console && window.console['firebug'])
  18682. {
  18683. return true;
  18684. }
  18685. if (window.console)
  18686. {
  18687. console.profile();
  18688. console.profileEnd();
  18689. if (console.clear)
  18690. {
  18691. console.clear();
  18692. }
  18693. return console['profiles'].length > 0;
  18694. }
  18695. return false;
  18696. }
  18697. };
  18698. /**
  18699. * @author Richard Davey <rich@photonstorm.com>
  18700. * @copyright 2013 Photon Storm Ltd.
  18701. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  18702. */
  18703. /**
  18704. * Abstracts away the use of RAF or setTimeOut for the core game update loop.
  18705. *
  18706. * @class Phaser.RequestAnimationFrame
  18707. * @constructor
  18708. * @param {Phaser.Game} game - A reference to the currently running game.
  18709. */
  18710. Phaser.RequestAnimationFrame = function(game) {
  18711. /**
  18712. * @property {Phaser.Game} game - The currently running game.
  18713. */
  18714. this.game = game;
  18715. /**
  18716. * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false.
  18717. * @default
  18718. */
  18719. this.isRunning = false;
  18720. var vendors = [
  18721. 'ms',
  18722. 'moz',
  18723. 'webkit',
  18724. 'o'
  18725. ];
  18726. for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++)
  18727. {
  18728. window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
  18729. window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'];
  18730. }
  18731. /**
  18732. * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf.
  18733. * @private
  18734. */
  18735. this._isSetTimeOut = false;
  18736. /**
  18737. * @property {function} _onLoop - The function called by the update.
  18738. * @private
  18739. */
  18740. this._onLoop = null;
  18741. /**
  18742. * @property {number} _timeOutID - The callback ID used when calling cancel.
  18743. * @private
  18744. */
  18745. this._timeOutID = null;
  18746. };
  18747. Phaser.RequestAnimationFrame.prototype = {
  18748. /**
  18749. * Starts the requestAnimatioFrame running or setTimeout if unavailable in browser
  18750. * @method Phaser.RequestAnimationFrame#start
  18751. */
  18752. start: function () {
  18753. this.isRunning = true;
  18754. var _this = this;
  18755. if (!window.requestAnimationFrame)
  18756. {
  18757. this._isSetTimeOut = true;
  18758. this._onLoop = function () {
  18759. return _this.updateSetTimeout();
  18760. };
  18761. this._timeOutID = window.setTimeout(this._onLoop, 0);
  18762. }
  18763. else
  18764. {
  18765. this._isSetTimeOut = false;
  18766. this._onLoop = function (time) {
  18767. return _this.updateRAF(time);
  18768. };
  18769. this._timeOutID = window.requestAnimationFrame(this._onLoop);
  18770. }
  18771. },
  18772. /**
  18773. * The update method for the requestAnimationFrame
  18774. * @method Phaser.RequestAnimationFrame#updateRAF
  18775. * @param {number} time - A timestamp, either from RAF or setTimeOut
  18776. */
  18777. updateRAF: function (time) {
  18778. this.game.update(time);
  18779. this._timeOutID = window.requestAnimationFrame(this._onLoop);
  18780. },
  18781. /**
  18782. * The update method for the setTimeout.
  18783. * @method Phaser.RequestAnimationFrame#updateSetTimeout
  18784. */
  18785. updateSetTimeout: function () {
  18786. this.game.update(Date.now());
  18787. this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall);
  18788. },
  18789. /**
  18790. * Stops the requestAnimationFrame from running.
  18791. * @method Phaser.RequestAnimationFrame#stop
  18792. */
  18793. stop: function () {
  18794. if (this._isSetTimeOut)
  18795. {
  18796. clearTimeout(this._timeOutID);
  18797. }
  18798. else
  18799. {
  18800. window.cancelAnimationFrame(this._timeOutID);
  18801. }
  18802. this.isRunning = false;
  18803. },
  18804. /**
  18805. * Is the browser using setTimeout?
  18806. * @method Phaser.RequestAnimationFrame#isSetTimeOut
  18807. * @return {boolean}
  18808. */
  18809. isSetTimeOut: function () {
  18810. return this._isSetTimeOut;
  18811. },
  18812. /**
  18813. * Is the browser using requestAnimationFrame?
  18814. * @method Phaser.RequestAnimationFrame#isRAF
  18815. * @return {boolean}
  18816. */
  18817. isRAF: function () {
  18818. return (this._isSetTimeOut === false);
  18819. }
  18820. };
  18821. /* jshint noempty: false */
  18822. /**
  18823. * @author Richard Davey <rich@photonstorm.com>
  18824. * @copyright 2013 Photon Storm Ltd.
  18825. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  18826. */
  18827. /**
  18828. * Phaser.RandomDataGenerator constructor.
  18829. *
  18830. * @class Phaser.RandomDataGenerator
  18831. * @classdesc An extremely useful repeatable random data generator. Access it via Phaser.Game.rnd
  18832. * Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense.
  18833. * Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript
  18834. *
  18835. * @constructor
  18836. * @param {array} seeds
  18837. */
  18838. Phaser.RandomDataGenerator = function (seeds) {
  18839. if (typeof seeds === "undefined") { seeds = []; }
  18840. /**
  18841. * @property {number} c - Internal var.
  18842. * @private
  18843. */
  18844. this.c = 1;
  18845. /**
  18846. * @property {number} s0 - Internal var.
  18847. * @private
  18848. */
  18849. this.s0 = 0;
  18850. /**
  18851. * @property {number} s1 - Internal var.
  18852. * @private
  18853. */
  18854. this.s1 = 0;
  18855. /**
  18856. * @property {number} s2 - Internal var.
  18857. * @private
  18858. */
  18859. this.s2 = 0;
  18860. this.sow(seeds);
  18861. };
  18862. Phaser.RandomDataGenerator.prototype = {
  18863. /**
  18864. * Private random helper.
  18865. * @method Phaser.RandomDataGenerator#rnd
  18866. * @private
  18867. * @return {number}
  18868. */
  18869. rnd: function () {
  18870. var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
  18871. this.c = t | 0;
  18872. this.s0 = this.s1;
  18873. this.s1 = this.s2;
  18874. this.s2 = t - this.c;
  18875. return this.s2;
  18876. },
  18877. /**
  18878. * Reset the seed of the random data generator.
  18879. *
  18880. * @method Phaser.RandomDataGenerator#sow
  18881. * @param {array} seeds
  18882. */
  18883. sow: function (seeds) {
  18884. if (typeof seeds === "undefined") { seeds = []; }
  18885. this.s0 = this.hash(' ');
  18886. this.s1 = this.hash(this.s0);
  18887. this.s2 = this.hash(this.s1);
  18888. this.c = 1;
  18889. var seed;
  18890. for (var i = 0; seed = seeds[i++]; )
  18891. {
  18892. this.s0 -= this.hash(seed);
  18893. this.s0 += ~~(this.s0 < 0);
  18894. this.s1 -= this.hash(seed);
  18895. this.s1 += ~~(this.s1 < 0);
  18896. this.s2 -= this.hash(seed);
  18897. this.s2 += ~~(this.s2 < 0);
  18898. }
  18899. },
  18900. /**
  18901. * Internal method that creates a seed hash.
  18902. * @method Phaser.RandomDataGenerator#hash
  18903. * @param {Any} data
  18904. * @private
  18905. * @return {number} hashed value.
  18906. */
  18907. hash: function (data) {
  18908. var h, i, n;
  18909. n = 0xefc8249d;
  18910. data = data.toString();
  18911. for (i = 0; i < data.length; i++) {
  18912. n += data.charCodeAt(i);
  18913. h = 0.02519603282416938 * n;
  18914. n = h >>> 0;
  18915. h -= n;
  18916. h *= n;
  18917. n = h >>> 0;
  18918. h -= n;
  18919. n += h * 0x100000000;// 2^32
  18920. }
  18921. return (n >>> 0) * 2.3283064365386963e-10;// 2^-32
  18922. },
  18923. /**
  18924. * Returns a random integer between 0 and 2^32.
  18925. * @method Phaser.RandomDataGenerator#integer
  18926. * @return {number} A random integer between 0 and 2^32.
  18927. */
  18928. integer: function() {
  18929. return this.rnd.apply(this) * 0x100000000;// 2^32
  18930. },
  18931. /**
  18932. * Returns a random real number between 0 and 1.
  18933. * @method Phaser.RandomDataGenerator#frac
  18934. * @return {number} A random real number between 0 and 1.
  18935. */
  18936. frac: function() {
  18937. return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16;// 2^-53
  18938. },
  18939. /**
  18940. * Returns a random real number between 0 and 2^32.
  18941. * @method Phaser.RandomDataGenerator#real
  18942. * @return {number} A random real number between 0 and 2^32.
  18943. */
  18944. real: function() {
  18945. return this.integer() + this.frac();
  18946. },
  18947. /**
  18948. * Returns a random integer between min and max.
  18949. * @method Phaser.RandomDataGenerator#integerInRange
  18950. * @param {number} min - The minimum value in the range.
  18951. * @param {number} max - The maximum value in the range.
  18952. * @return {number} A random number between min and max.
  18953. */
  18954. integerInRange: function (min, max) {
  18955. return Math.floor(this.realInRange(min, max));
  18956. },
  18957. /**
  18958. * Returns a random real number between min and max.
  18959. * @method Phaser.RandomDataGenerator#realInRange
  18960. * @param {number} min - The minimum value in the range.
  18961. * @param {number} max - The maximum value in the range.
  18962. * @return {number} A random number between min and max.
  18963. */
  18964. realInRange: function (min, max) {
  18965. return this.frac() * (max - min) + min;
  18966. },
  18967. /**
  18968. * Returns a random real number between -1 and 1.
  18969. * @method Phaser.RandomDataGenerator#normal
  18970. * @return {number} A random real number between -1 and 1.
  18971. */
  18972. normal: function () {
  18973. return 1 - 2 * this.frac();
  18974. },
  18975. /**
  18976. * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
  18977. * @method Phaser.RandomDataGenerator#uuid
  18978. * @return {string} A valid RFC4122 version4 ID hex string
  18979. */
  18980. uuid: function () {
  18981. var a = '';
  18982. var b = '';
  18983. for (b = a = ''; a++ < 36; b +=~a % 5 | a * 3&4 ? (a^15 ? 8^this.frac() * (a^20 ? 16 : 4) : 4).toString(16) : '-')
  18984. {
  18985. }
  18986. return b;
  18987. },
  18988. /**
  18989. * Returns a random member of `array`.
  18990. * @method Phaser.RandomDataGenerator#pick
  18991. * @param {Array} ary - An Array to pick a random member of.
  18992. * @return {any} A random member of the array.
  18993. */
  18994. pick: function (ary) {
  18995. return ary[this.integerInRange(0, ary.length)];
  18996. },
  18997. /**
  18998. * Returns a random member of `array`, favoring the earlier entries.
  18999. * @method Phaser.RandomDataGenerator#weightedPick
  19000. * @param {Array} ary - An Array to pick a random member of.
  19001. * @return {any} A random member of the array.
  19002. */
  19003. weightedPick: function (ary) {
  19004. return ary[~~(Math.pow(this.frac(), 2) * ary.length)];
  19005. },
  19006. /**
  19007. * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified.
  19008. * @method Phaser.RandomDataGenerator#timestamp
  19009. * @param {number} min - The minimum value in the range.
  19010. * @param {number} max - The maximum value in the range.
  19011. * @return {number} A random timestamp between min and max.
  19012. */
  19013. timestamp: function (min, max) {
  19014. return this.realInRange(min || 946684800000, max || 1577862000000);
  19015. },
  19016. /**
  19017. * Returns a random angle between -180 and 180.
  19018. * @method Phaser.RandomDataGenerator#angle
  19019. * @return {number} A random number between -180 and 180.
  19020. */
  19021. angle: function() {
  19022. return this.integerInRange(-180, 180);
  19023. }
  19024. };
  19025. /**
  19026. * @author Richard Davey <rich@photonstorm.com>
  19027. * @copyright 2013 Photon Storm Ltd.
  19028. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19029. */
  19030. /**
  19031. * A collection of mathematical methods.
  19032. *
  19033. * @class Phaser.Math
  19034. */
  19035. Phaser.Math = {
  19036. /**
  19037. * = 2 &pi;
  19038. * @method Phaser.Math#PI2
  19039. */
  19040. PI2: Math.PI * 2,
  19041. /**
  19042. * Two number are fuzzyEqual if their difference is less than &epsilon;.
  19043. * @method Phaser.Math#fuzzyEqual
  19044. * @param {number} a
  19045. * @param {number} b
  19046. * @param {number} epsilon
  19047. * @return {boolean} True if |a-b|<&epsilon;
  19048. */
  19049. fuzzyEqual: function (a, b, epsilon) {
  19050. if (typeof epsilon === "undefined") { epsilon = 0.0001; }
  19051. return Math.abs(a - b) < epsilon;
  19052. },
  19053. /**
  19054. * a is fuzzyLessThan b if it is less than b + &epsilon;.
  19055. * @method Phaser.Math#fuzzyEqual
  19056. * @param {number} a
  19057. * @param {number} b
  19058. * @param {number} epsilon
  19059. * @return {boolean} True if a<b+&epsilon;
  19060. */
  19061. fuzzyLessThan: function (a, b, epsilon) {
  19062. if (typeof epsilon === "undefined") { epsilon = 0.0001; }
  19063. return a < b + epsilon;
  19064. },
  19065. /**
  19066. * a is fuzzyGreaterThan b if it is more than b - &epsilon;.
  19067. * @method Phaser.Math#fuzzyGreaterThan
  19068. * @param {number} a
  19069. * @param {number} b
  19070. * @param {number} epsilon
  19071. * @return {boolean} True if a>b+&epsilon;
  19072. */
  19073. fuzzyGreaterThan: function (a, b, epsilon) {
  19074. if (typeof epsilon === "undefined") { epsilon = 0.0001; }
  19075. return a > b - epsilon;
  19076. },
  19077. /**
  19078. * @method Phaser.Math#fuzzyCeil
  19079. * @param {number} val
  19080. * @param {number} epsilon
  19081. * @return {boolean} ceiling(val-&epsilon;)
  19082. */
  19083. fuzzyCeil: function (val, epsilon) {
  19084. if (typeof epsilon === "undefined") { epsilon = 0.0001; }
  19085. return Math.ceil(val - epsilon);
  19086. },
  19087. /**
  19088. * @method Phaser.Math#fuzzyFloor
  19089. * @param {number} val
  19090. * @param {number} epsilon
  19091. * @return {boolean} floor(val-&epsilon;)
  19092. */
  19093. fuzzyFloor: function (val, epsilon) {
  19094. if (typeof epsilon === "undefined") { epsilon = 0.0001; }
  19095. return Math.floor(val + epsilon);
  19096. },
  19097. /**
  19098. * Averages all values passed to the function and returns the result. You can pass as many parameters as you like.
  19099. * @method Phaser.Math#average
  19100. * @return {number} The average of all given values.
  19101. */
  19102. average: function () {
  19103. var args = [];
  19104. for (var _i = 0; _i < (arguments.length - 0); _i++) {
  19105. args[_i] = arguments[_i + 0];
  19106. }
  19107. var avg = 0;
  19108. for (var i = 0; i < args.length; i++) {
  19109. avg += args[i];
  19110. }
  19111. return avg / args.length;
  19112. },
  19113. /**
  19114. * @method Phaser.Math#truncate
  19115. * @param {number} n
  19116. * @return {number}
  19117. */
  19118. truncate: function (n) {
  19119. return (n > 0) ? Math.floor(n) : Math.ceil(n);
  19120. },
  19121. /**
  19122. * @method Phaser.Math#shear
  19123. * @param {number} n
  19124. * @return {number} n mod 1
  19125. */
  19126. shear: function (n) {
  19127. return n % 1;
  19128. },
  19129. /**
  19130. * Snap a value to nearest grid slice, using rounding.
  19131. *
  19132. * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15.
  19133. *
  19134. * @method Phaser.Math#snapTo
  19135. * @param {number} input - The value to snap.
  19136. * @param {number} gap - The interval gap of the grid.
  19137. * @param {number} [start] - Optional starting offset for gap.
  19138. * @return {number}
  19139. */
  19140. snapTo: function (input, gap, start) {
  19141. if (typeof start === "undefined") { start = 0; }
  19142. if (gap === 0) {
  19143. return input;
  19144. }
  19145. input -= start;
  19146. input = gap * Math.round(input / gap);
  19147. return start + input;
  19148. },
  19149. /**
  19150. * Snap a value to nearest grid slice, using floor.
  19151. *
  19152. * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. As will 14 snap to 10... but 16 will snap to 15
  19153. *
  19154. * @method Phaser.Math#snapToFloor
  19155. * @param {number} input - The value to snap.
  19156. * @param {number} gap - The interval gap of the grid.
  19157. * @param {number} [start] - Optional starting offset for gap.
  19158. * @return {number}
  19159. */
  19160. snapToFloor: function (input, gap, start) {
  19161. if (typeof start === "undefined") { start = 0; }
  19162. if (gap === 0) {
  19163. return input;
  19164. }
  19165. input -= start;
  19166. input = gap * Math.floor(input / gap);
  19167. return start + input;
  19168. },
  19169. /**
  19170. * Snap a value to nearest grid slice, using ceil.
  19171. *
  19172. * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20.
  19173. *
  19174. * @method Phaser.Math#snapToCeil
  19175. * @param {number} input - The value to snap.
  19176. * @param {number} gap - The interval gap of the grid.
  19177. * @param {number} [start] - Optional starting offset for gap.
  19178. * @return {number}
  19179. */
  19180. snapToCeil: function (input, gap, start) {
  19181. if (typeof start === "undefined") { start = 0; }
  19182. if (gap === 0) {
  19183. return input;
  19184. }
  19185. input -= start;
  19186. input = gap * Math.ceil(input / gap);
  19187. return start + input;
  19188. },
  19189. /**
  19190. * Snaps a value to the nearest value in an array.
  19191. * @method Phaser.Math#snapToInArray
  19192. * @param {number} input
  19193. * @param {array} arr
  19194. * @param {boolean} sort - True if the array needs to be sorted.
  19195. * @return {number}
  19196. */
  19197. snapToInArray: function (input, arr, sort) {
  19198. if (typeof sort === "undefined") { sort = true; }
  19199. if (sort) {
  19200. arr.sort();
  19201. }
  19202. if (input < arr[0]) {
  19203. return arr[0];
  19204. }
  19205. var i = 1;
  19206. while (arr[i] < input) {
  19207. i++;
  19208. }
  19209. var low = arr[i - 1];
  19210. var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY;
  19211. return ((high - input) <= (input - low)) ? high : low;
  19212. },
  19213. /**
  19214. * Round to some place comparative to a 'base', default is 10 for decimal place.
  19215. *
  19216. * 'place' is represented by the power applied to 'base' to get that place
  19217. * e.g.
  19218. * 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011
  19219. *
  19220. * roundTo(2000/7,3) === 0
  19221. * roundTo(2000/7,2) == 300
  19222. * roundTo(2000/7,1) == 290
  19223. * roundTo(2000/7,0) == 286
  19224. * roundTo(2000/7,-1) == 285.7
  19225. * roundTo(2000/7,-2) == 285.71
  19226. * roundTo(2000/7,-3) == 285.714
  19227. * roundTo(2000/7,-4) == 285.7143
  19228. * roundTo(2000/7,-5) == 285.71429
  19229. *
  19230. * roundTo(2000/7,3,2) == 288 -- 100100000
  19231. * roundTo(2000/7,2,2) == 284 -- 100011100
  19232. * roundTo(2000/7,1,2) == 286 -- 100011110
  19233. * roundTo(2000/7,0,2) == 286 -- 100011110
  19234. * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1
  19235. * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11
  19236. * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11
  19237. * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011
  19238. * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111
  19239. *
  19240. * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed
  19241. * because we are rounding 100011.1011011011011011 which rounds up.
  19242. *
  19243. * @method Phaser.Math#roundTo
  19244. * @param {number} value - The value to round.
  19245. * @param {number} place - The place to round to.
  19246. * @param {number} base - The base to round in... default is 10 for decimal.
  19247. * @return {number}
  19248. */
  19249. roundTo: function (value, place, base) {
  19250. if (typeof place === "undefined") { place = 0; }
  19251. if (typeof base === "undefined") { base = 10; }
  19252. var p = Math.pow(base, -place);
  19253. return Math.round(value * p) / p;
  19254. },
  19255. /**
  19256. * @method Phaser.Math#floorTo
  19257. * @param {number} value - The value to round.
  19258. * @param {number} place - The place to round to.
  19259. * @param {number} base - The base to round in... default is 10 for decimal.
  19260. * @return {number}
  19261. */
  19262. floorTo: function (value, place, base) {
  19263. if (typeof place === "undefined") { place = 0; }
  19264. if (typeof base === "undefined") { base = 10; }
  19265. var p = Math.pow(base, -place);
  19266. return Math.floor(value * p) / p;
  19267. },
  19268. /**
  19269. * @method Phaser.Math#ceilTo
  19270. * @param {number} value - The value to round.
  19271. * @param {number} place - The place to round to.
  19272. * @param {number} base - The base to round in... default is 10 for decimal.
  19273. * @return {number}
  19274. */
  19275. ceilTo: function (value, place, base) {
  19276. if (typeof place === "undefined") { place = 0; }
  19277. if (typeof base === "undefined") { base = 10; }
  19278. var p = Math.pow(base, -place);
  19279. return Math.ceil(value * p) / p;
  19280. },
  19281. /**
  19282. * A one dimensional linear interpolation of a value.
  19283. * @method Phaser.Math#interpolateFloat
  19284. * @param {number} a
  19285. * @param {number} b
  19286. * @param {number} weight
  19287. * @return {number}
  19288. */
  19289. interpolateFloat: function (a, b, weight) {
  19290. return (b - a) * weight + a;
  19291. },
  19292. /**
  19293. * Find the angle of a segment from (x1, y1) -> (x2, y2 ).
  19294. * @method Phaser.Math#angleBetween
  19295. * @param {number} x1
  19296. * @param {number} y1
  19297. * @param {number} x2
  19298. * @param {number} y2
  19299. * @return {number}
  19300. */
  19301. angleBetween: function (x1, y1, x2, y2) {
  19302. return Math.atan2(y2 - y1, x2 - x1);
  19303. },
  19304. /**
  19305. * Set an angle within the bounds of -&pi; to&pi;.
  19306. * @method Phaser.Math#normalizeAngle
  19307. * @param {number} angle
  19308. * @param {boolean} radians - True if angle size is expressed in radians.
  19309. * @return {number}
  19310. */
  19311. normalizeAngle: function (angle, radians) {
  19312. if (typeof radians === "undefined") { radians = true; }
  19313. var rd = (radians) ? Math.PI : 180;
  19314. return this.wrap(angle, -rd, rd);
  19315. },
  19316. /**
  19317. * Closest angle between two angles from a1 to a2
  19318. * absolute value the return for exact angle
  19319. * @method Phaser.Math#nearestAngleBetween
  19320. * @param {number} a1
  19321. * @param {number} a2
  19322. * @param {boolean} radians - True if angle sizes are expressed in radians.
  19323. * @return {number}
  19324. */
  19325. nearestAngleBetween: function (a1, a2, radians) {
  19326. if (typeof radians === "undefined") { radians = true; }
  19327. var rd = (radians) ? Math.PI : 180;
  19328. a1 = this.normalizeAngle(a1, radians);
  19329. a2 = this.normalizeAngle(a2, radians);
  19330. if (a1 < -rd / 2 && a2 > rd / 2)
  19331. {
  19332. a1 += rd * 2;
  19333. }
  19334. if (a2 < -rd / 2 && a1 > rd / 2)
  19335. {
  19336. a2 += rd * 2;
  19337. }
  19338. return a2 - a1;
  19339. },
  19340. /**
  19341. * Interpolate across the shortest arc between two angles.
  19342. * @method Phaser.Math#interpolateAngles
  19343. * @param {number} a1 - Description.
  19344. * @param {number} a2 - Description.
  19345. * @param {number} weight - Description.
  19346. * @param {boolean} radians - True if angle sizes are expressed in radians.
  19347. * @param {Description} ease - Description.
  19348. * @return {number}
  19349. */
  19350. interpolateAngles: function (a1, a2, weight, radians, ease) {
  19351. if (typeof radians === "undefined") { radians = true; }
  19352. if (typeof ease === "undefined") { ease = null; }
  19353. a1 = this.normalizeAngle(a1, radians);
  19354. a2 = this.normalizeAngleToAnother(a2, a1, radians);
  19355. return (typeof ease === 'function') ? ease(weight, a1, a2 - a1, 1) : this.interpolateFloat(a1, a2, weight);
  19356. },
  19357. /**
  19358. * Generate a random bool result based on the chance value.
  19359. * <p>
  19360. * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance
  19361. * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed.
  19362. * </p>
  19363. * @method Phaser.Math#chanceRoll
  19364. * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%).
  19365. * @return {boolean} True if the roll passed, or false otherwise.
  19366. */
  19367. chanceRoll: function (chance) {
  19368. if (typeof chance === "undefined") { chance = 50; }
  19369. if (chance <= 0)
  19370. {
  19371. return false;
  19372. }
  19373. else if (chance >= 100)
  19374. {
  19375. return true;
  19376. }
  19377. else
  19378. {
  19379. if (Math.random() * 100 >= chance)
  19380. {
  19381. return false;
  19382. }
  19383. else
  19384. {
  19385. return true;
  19386. }
  19387. }
  19388. },
  19389. /**
  19390. * Returns an Array containing the numbers from min to max (inclusive).
  19391. *
  19392. * @method Phaser.Math#numberArray
  19393. * @param {number} min - The minimum value the array starts with.
  19394. * @param {number} max - The maximum value the array contains.
  19395. * @return {array} The array of number values.
  19396. */
  19397. numberArray: function (min, max) {
  19398. var result = [];
  19399. for (var i = min; i <= max; i++)
  19400. {
  19401. result.push(i);
  19402. }
  19403. return result;
  19404. },
  19405. /**
  19406. * Adds the given amount to the value, but never lets the value go over the specified maximum.
  19407. *
  19408. * @method Phaser.Math#maxAdd
  19409. * @param {number} value - The value to add the amount to.
  19410. * @param {number} amount - The amount to add to the value.
  19411. * @param {number} max- The maximum the value is allowed to be.
  19412. * @return {number}
  19413. */
  19414. maxAdd: function (value, amount, max) {
  19415. value += amount;
  19416. if (value > max)
  19417. {
  19418. value = max;
  19419. }
  19420. return value;
  19421. },
  19422. /**
  19423. * Subtracts the given amount from the value, but never lets the value go below the specified minimum.
  19424. *
  19425. * @method Phaser.Math#minSub
  19426. * @param {number} value - The base value.
  19427. * @param {number} amount - The amount to subtract from the base value.
  19428. * @param {number} min - The minimum the value is allowed to be.
  19429. * @return {number} The new value.
  19430. */
  19431. minSub: function (value, amount, min) {
  19432. value -= amount;
  19433. if (value < min)
  19434. {
  19435. value = min;
  19436. }
  19437. return value;
  19438. },
  19439. /**
  19440. * Ensures that the value always stays between min and max, by wrapping the value around.
  19441. * <p>max should be larger than min, or the function will return 0</p>
  19442. *
  19443. * @method Phaser.Math#wrap
  19444. * @param value The value to wrap
  19445. * @param min The minimum the value is allowed to be
  19446. * @param max The maximum the value is allowed to be
  19447. * @return {number} The wrapped value
  19448. */
  19449. wrap: function (value, min, max) {
  19450. var range = max - min;
  19451. if (range <= 0)
  19452. {
  19453. return 0;
  19454. }
  19455. var result = (value - min) % range;
  19456. if (result < 0)
  19457. {
  19458. result += range;
  19459. }
  19460. return result + min;
  19461. },
  19462. /**
  19463. * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around.
  19464. * <p>Values must be positive integers, and are passed through Math.abs</p>
  19465. *
  19466. * @method Phaser.Math#wrapValue
  19467. * @param {number} value - The value to add the amount to.
  19468. * @param {number} amount - The amount to add to the value.
  19469. * @param {number} max - The maximum the value is allowed to be.
  19470. * @return {number} The wrapped value.
  19471. */
  19472. wrapValue: function (value, amount, max) {
  19473. var diff;
  19474. value = Math.abs(value);
  19475. amount = Math.abs(amount);
  19476. max = Math.abs(max);
  19477. diff = (value + amount) % max;
  19478. return diff;
  19479. },
  19480. /**
  19481. * Randomly returns either a 1 or -1.
  19482. *
  19483. * @method Phaser.Math#randomSign
  19484. * @return {number} 1 or -1
  19485. */
  19486. randomSign: function () {
  19487. return (Math.random() > 0.5) ? 1 : -1;
  19488. },
  19489. /**
  19490. * Returns true if the number given is odd.
  19491. *
  19492. * @method Phaser.Math#isOdd
  19493. * @param {number} n - The number to check.
  19494. * @return {boolean} True if the given number is odd. False if the given number is even.
  19495. */
  19496. isOdd: function (n) {
  19497. return (n & 1);
  19498. },
  19499. /**
  19500. * Returns true if the number given is even.
  19501. *
  19502. * @method Phaser.Math#isEven
  19503. * @param {number} n - The number to check.
  19504. * @return {boolean} True if the given number is even. False if the given number is odd.
  19505. */
  19506. isEven: function (n) {
  19507. if (n & 1)
  19508. {
  19509. return false;
  19510. }
  19511. else
  19512. {
  19513. return true;
  19514. }
  19515. },
  19516. /**
  19517. * Significantly faster version of Math.max
  19518. * See http://jsperf.com/math-s-min-max-vs-homemade/5
  19519. *
  19520. * @method Phaser.Math#max
  19521. * @return {number} The highest value from those given.
  19522. */
  19523. max: function () {
  19524. for (var i = 1, max = 0, len = arguments.length; i < len; i++)
  19525. {
  19526. if (arguments[max] < arguments[i])
  19527. {
  19528. max = i;
  19529. }
  19530. }
  19531. return arguments[max];
  19532. },
  19533. /**
  19534. * Significantly faster version of Math.min
  19535. * See http://jsperf.com/math-s-min-max-vs-homemade/5
  19536. *
  19537. * @method Phaser.Math#min
  19538. * @return {number} The lowest value from those given.
  19539. */
  19540. min: function () {
  19541. for (var i =1 , min = 0, len = arguments.length; i < len; i++)
  19542. {
  19543. if (arguments[i] < arguments[min])
  19544. {
  19545. min = i;
  19546. }
  19547. }
  19548. return arguments[min];
  19549. },
  19550. /**
  19551. * Keeps an angle value between -180 and +180<br>
  19552. * Should be called whenever the angle is updated on the Sprite to stop it from going insane.
  19553. *
  19554. * @method Phaser.Math#wrapAngle
  19555. * @param {number} angle - The angle value to check
  19556. * @return {number} The new angle value, returns the same as the input angle if it was within bounds.
  19557. */
  19558. wrapAngle: function (angle) {
  19559. return this.wrap(angle, -180, 180);
  19560. },
  19561. /**
  19562. * Keeps an angle value between the given min and max values.
  19563. *
  19564. * @method Phaser.Math#angleLimit
  19565. * @param {number} angle - The angle value to check. Must be between -180 and +180.
  19566. * @param {number} min - The minimum angle that is allowed (must be -180 or greater).
  19567. * @param {number} max - The maximum angle that is allowed (must be 180 or less).
  19568. *
  19569. * @return {number} The new angle value, returns the same as the input angle if it was within bounds
  19570. */
  19571. angleLimit: function (angle, min, max) {
  19572. var result = angle;
  19573. if (angle > max)
  19574. {
  19575. result = max;
  19576. }
  19577. else if (angle < min)
  19578. {
  19579. result = min;
  19580. }
  19581. return result;
  19582. },
  19583. /**
  19584. * Description.
  19585. * @method Phaser.Math#linearInterpolation
  19586. * @param {number} v
  19587. * @param {number} k
  19588. * @return {number}
  19589. */
  19590. linearInterpolation: function (v, k) {
  19591. var m = v.length - 1;
  19592. var f = m * k;
  19593. var i = Math.floor(f);
  19594. if (k < 0)
  19595. {
  19596. return this.linear(v[0], v[1], f);
  19597. }
  19598. if (k > 1)
  19599. {
  19600. return this.linear(v[m], v[m - 1], m - f);
  19601. }
  19602. return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i);
  19603. },
  19604. /**
  19605. * Description.
  19606. * @method Phaser.Math#bezierInterpolation
  19607. * @param {number} v
  19608. * @param {number} k
  19609. * @return {number}
  19610. */
  19611. bezierInterpolation: function (v, k) {
  19612. var b = 0;
  19613. var n = v.length - 1;
  19614. for (var i = 0; i <= n; i++)
  19615. {
  19616. b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * this.bernstein(n, i);
  19617. }
  19618. return b;
  19619. },
  19620. /**
  19621. * Description.
  19622. * @method Phaser.Math#catmullRomInterpolation
  19623. * @param {number} v
  19624. * @param {number} k
  19625. * @return {number}
  19626. */
  19627. catmullRomInterpolation: function (v, k) {
  19628. var m = v.length - 1;
  19629. var f = m * k;
  19630. var i = Math.floor(f);
  19631. if (v[0] === v[m])
  19632. {
  19633. if (k < 0)
  19634. {
  19635. i = Math.floor(f = m * (1 + k));
  19636. }
  19637. return this.catmullRom(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
  19638. }
  19639. else
  19640. {
  19641. if (k < 0)
  19642. {
  19643. return v[0] - (this.catmullRom(v[0], v[0], v[1], v[1], -f) - v[0]);
  19644. }
  19645. if (k > 1)
  19646. {
  19647. return v[m] - (this.catmullRom(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  19648. }
  19649. return this.catmullRom(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
  19650. }
  19651. },
  19652. /**
  19653. * Description.
  19654. * @method Phaser.Math#Linear
  19655. * @param {number} p0
  19656. * @param {number} p1
  19657. * @param {number} t
  19658. * @return {number}
  19659. */
  19660. linear: function (p0, p1, t) {
  19661. return (p1 - p0) * t + p0;
  19662. },
  19663. /**
  19664. * @method Phaser.Math#bernstein
  19665. * @param {number} n
  19666. * @param {number} i
  19667. * @return {number}
  19668. */
  19669. bernstein: function (n, i) {
  19670. return this.factorial(n) / this.factorial(i) / this.factorial(n - i);
  19671. },
  19672. /**
  19673. * Description.
  19674. * @method Phaser.Math#catmullRom
  19675. * @param {number} p0
  19676. * @param {number} p1
  19677. * @param {number} p2
  19678. * @param {number} p3
  19679. * @param {number} t
  19680. * @return {number}
  19681. */
  19682. catmullRom: function (p0, p1, p2, p3, t) {
  19683. var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2;
  19684. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  19685. },
  19686. /**
  19687. * @method Phaser.Math#difference
  19688. * @param {number} a
  19689. * @param {number} b
  19690. * @return {number}
  19691. */
  19692. difference: function (a, b) {
  19693. return Math.abs(a - b);
  19694. },
  19695. /**
  19696. * Fetch a random entry from the given array.
  19697. * Will return null if random selection is missing, or array has no entries.
  19698. *
  19699. * @method Phaser.Math#getRandom
  19700. * @param {array} objects - An array of objects.
  19701. * @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
  19702. * @param {number} length - Optional restriction on the number of values you want to randomly select from.
  19703. * @return {object} The random object that was selected.
  19704. */
  19705. getRandom: function (objects, startIndex, length) {
  19706. if (typeof startIndex === "undefined") { startIndex = 0; }
  19707. if (typeof length === "undefined") { length = 0; }
  19708. if (objects != null) {
  19709. var l = length;
  19710. if ((l === 0) || (l > objects.length - startIndex))
  19711. {
  19712. l = objects.length - startIndex;
  19713. }
  19714. if (l > 0)
  19715. {
  19716. return objects[startIndex + Math.floor(Math.random() * l)];
  19717. }
  19718. }
  19719. return null;
  19720. },
  19721. /**
  19722. * Round down to the next whole number. E.g. floor(1.7) == 1, and floor(-2.7) == -2.
  19723. *
  19724. * @method Phaser.Math#floor
  19725. * @param {number} Value Any number.
  19726. * @return {number} The rounded value of that number.
  19727. */
  19728. floor: function (value) {
  19729. var n = value | 0;
  19730. return (value > 0) ? (n) : ((n != value) ? (n - 1) : (n));
  19731. },
  19732. /**
  19733. * Round up to the next whole number. E.g. ceil(1.3) == 2, and ceil(-2.3) == -3.
  19734. *
  19735. * @method Phaser.Math#ceil
  19736. * @param {number} value - Any number.
  19737. * @return {number} The rounded value of that number.
  19738. */
  19739. ceil: function (value) {
  19740. var n = value | 0;
  19741. return (value > 0) ? ((n != value) ? (n + 1) : (n)) : (n);
  19742. },
  19743. /**
  19744. * Generate a sine and cosine table simultaneously and extremely quickly. Based on research by Franky of scene.at
  19745. * <p>
  19746. * The parameters allow you to specify the length, amplitude and frequency of the wave. Once you have called this function
  19747. * you should get the results via getSinTable() and getCosTable(). This generator is fast enough to be used in real-time.
  19748. * </p>
  19749. * @method Phaser.Math#sinCosGenerator
  19750. * @param {number} length - The length of the wave
  19751. * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value
  19752. * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value
  19753. * @param {number} frequency - The frequency of the sine and cosine table data
  19754. * @return {Array} Returns the sine table
  19755. */
  19756. sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) {
  19757. if (typeof sinAmplitude === "undefined") { sinAmplitude = 1.0; }
  19758. if (typeof cosAmplitude === "undefined") { cosAmplitude = 1.0; }
  19759. if (typeof frequency === "undefined") { frequency = 1.0; }
  19760. var sin = sinAmplitude;
  19761. var cos = cosAmplitude;
  19762. var frq = frequency * Math.PI / length;
  19763. var cosTable = [];
  19764. var sinTable = [];
  19765. for (var c = 0; c < length; c++) {
  19766. cos -= sin * frq;
  19767. sin += cos * frq;
  19768. cosTable[c] = cos;
  19769. sinTable[c] = sin;
  19770. }
  19771. return { sin: sinTable, cos: cosTable, length: length };
  19772. },
  19773. /**
  19774. * Removes the top element from the stack and re-inserts it onto the bottom, then returns it.
  19775. * The original stack is modified in the process. This effectively moves the position of the data from the start to the end of the table.
  19776. *
  19777. * @method Phaser.Math#shift
  19778. * @param {array} stack - The array to shift.
  19779. * @return {any} The shifted value.
  19780. */
  19781. shift: function (stack) {
  19782. var s = stack.shift();
  19783. stack.push(s);
  19784. return s;
  19785. },
  19786. /**
  19787. * Shuffles the data in the given array into a new order
  19788. * @method Phaser.Math#shuffleArray
  19789. * @param {array} array - The array to shuffle
  19790. * @return {array} The array
  19791. */
  19792. shuffleArray: function (array) {
  19793. for (var i = array.length - 1; i > 0; i--) {
  19794. var j = Math.floor(Math.random() * (i + 1));
  19795. var temp = array[i];
  19796. array[i] = array[j];
  19797. array[j] = temp;
  19798. }
  19799. return array;
  19800. },
  19801. /**
  19802. * Returns the distance between the two given set of coordinates.
  19803. *
  19804. * @method Phaser.Math#distance
  19805. * @param {number} x1
  19806. * @param {number} y1
  19807. * @param {number} x2
  19808. * @param {number} y2
  19809. * @return {number} The distance between this Point object and the destination Point object.
  19810. */
  19811. distance: function (x1, y1, x2, y2) {
  19812. var dx = x1 - x2;
  19813. var dy = y1 - y2;
  19814. return Math.sqrt(dx * dx + dy * dy);
  19815. },
  19816. /**
  19817. * Returns the rounded distance between the two given set of coordinates.
  19818. *
  19819. * @method Phaser.Math#distanceRounded
  19820. * @param {number} x1
  19821. * @param {number} y1
  19822. * @param {number} x2
  19823. * @param {number} y2
  19824. * @return {number} The distance between this Point object and the destination Point object.
  19825. */
  19826. distanceRounded: function (x1, y1, x2, y2) {
  19827. return Math.round(Phaser.Math.distance(x1, y1, x2, y2));
  19828. },
  19829. /**
  19830. * Force a value within the boundaries of two values.
  19831. * Clamp value to range <a, b>
  19832. *
  19833. * @method Phaser.Math#clamp
  19834. * @param {number} x
  19835. * @param {number} a
  19836. * @param {number} b
  19837. * @return {number}
  19838. */
  19839. clamp: function ( x, a, b ) {
  19840. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  19841. },
  19842. /**
  19843. * Clamp value to range <a, inf).
  19844. *
  19845. * @method Phaser.Math#clampBottom
  19846. * @param {number} x
  19847. * @param {number} a
  19848. * @return {number}
  19849. */
  19850. clampBottom: function ( x, a ) {
  19851. return x < a ? a : x;
  19852. },
  19853. /**
  19854. * Checks if two values are within the given tolerance of each other.
  19855. *
  19856. * @method Phaser.Math#within
  19857. * @param {number} a - The first number to check
  19858. * @param {number} b - The second number to check
  19859. * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range.
  19860. * @return {boolean} True if a is <= tolerance of b.
  19861. */
  19862. within: function ( a, b, tolerance ) {
  19863. return (Math.abs(a - b) <= tolerance);
  19864. },
  19865. /**
  19866. * Linear mapping from range <a1, a2> to range <b1, b2>
  19867. *
  19868. * @method Phaser.Math#mapLinear
  19869. * @param {number} x
  19870. * @param {number} a1
  19871. * @param {number} a1
  19872. * @param {number} a2
  19873. * @param {number} b1
  19874. * @param {number} b2
  19875. * @return {number}
  19876. */
  19877. mapLinear: function ( x, a1, a2, b1, b2 ) {
  19878. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  19879. },
  19880. /**
  19881. * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
  19882. *
  19883. * @method Phaser.Math#smoothstep
  19884. * @param {number} x
  19885. * @param {number} min
  19886. * @param {number} max
  19887. * @return {number}
  19888. */
  19889. smoothstep: function ( x, min, max ) {
  19890. if (x <= min)
  19891. {
  19892. return 0;
  19893. }
  19894. if (x >= max)
  19895. {
  19896. return 1;
  19897. }
  19898. x = (x - min) / (max - min);
  19899. return x * x * (3 - 2 * x);
  19900. },
  19901. /**
  19902. * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
  19903. *
  19904. * @method Phaser.Math#smootherstep
  19905. * @param {number} x
  19906. * @param {number} min
  19907. * @param {number} max
  19908. * @return {number}
  19909. */
  19910. smootherstep: function ( x, min, max ) {
  19911. if (x <= min)
  19912. {
  19913. return 0;
  19914. }
  19915. if (x >= max)
  19916. {
  19917. return 1;
  19918. }
  19919. x = (x - min) / (max - min);
  19920. return x * x * x * (x * (x * 6 - 15) + 10);
  19921. },
  19922. /**
  19923. * A value representing the sign of the value.
  19924. * -1 for negative, +1 for positive, 0 if value is 0
  19925. *
  19926. * @method Phaser.Math#sign
  19927. * @param {number} x
  19928. * @return {number}
  19929. */
  19930. sign: function ( x ) {
  19931. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  19932. },
  19933. /**
  19934. * Convert degrees to radians.
  19935. *
  19936. * @method Phaser.Math#degToRad
  19937. * @return {function}
  19938. */
  19939. degToRad: function() {
  19940. var degreeToRadiansFactor = Math.PI / 180;
  19941. return function ( degrees ) {
  19942. return degrees * degreeToRadiansFactor;
  19943. };
  19944. }(),
  19945. /**
  19946. * Convert degrees to radians.
  19947. *
  19948. * @method Phaser.Math#radToDeg
  19949. * @return {function}
  19950. */
  19951. radToDeg: function() {
  19952. var radianToDegreesFactor = 180 / Math.PI;
  19953. return function ( radians ) {
  19954. return radians * radianToDegreesFactor;
  19955. };
  19956. }()
  19957. };
  19958. /**
  19959. * @author Richard Davey <rich@photonstorm.com>
  19960. * @copyright 2013 Photon Storm Ltd.
  19961. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19962. */
  19963. /**
  19964. * Javascript QuadTree
  19965. * @version 1.0
  19966. * @author Timo Hausmann
  19967. *
  19968. * @version 1.2, September 4th 2013
  19969. * @author Richard Davey
  19970. * The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked
  19971. * it massively to add node indexing, removed lots of temp. var creation and significantly
  19972. * increased performance as a result.
  19973. *
  19974. * Original version at https://github.com/timohausmann/quadtree-js/
  19975. */
  19976. /**
  19977. * @copyright © 2012 Timo Hausmann
  19978. *
  19979. * Permission is hereby granted, free of charge, to any person obtaining
  19980. * a copy of this software and associated documentation files (the
  19981. * "Software"), to deal in the Software without restriction, including
  19982. * without limitation the rights to use, copy, modify, merge, publish,
  19983. * distribute, sublicense, and/or sell copies of the Software, and to
  19984. * permit persons to whom the Software is furnished to do so, subject to
  19985. * the following conditions:
  19986. *
  19987. * The above copyright notice and this permission notice shall be
  19988. * included in all copies or substantial portions of the Software.
  19989. *
  19990. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  19991. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19992. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19993. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19994. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  19995. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  19996. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  19997. */
  19998. /**
  19999. * QuadTree Constructor
  20000. *
  20001. * @class Phaser.QuadTree
  20002. * @classdesc A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked
  20003. * it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. Original version at https://github.com/timohausmann/quadtree-js/
  20004. * @constructor
  20005. * @param {Description} physicsManager - Description.
  20006. * @param {Description} x - Description.
  20007. * @param {Description} y - Description.
  20008. * @param {number} width - The width of your game in game pixels.
  20009. * @param {number} height - The height of your game in game pixels.
  20010. * @param {number} maxObjects - Description.
  20011. * @param {number} maxLevels - Description.
  20012. * @param {number} level - Description.
  20013. */
  20014. Phaser.QuadTree = function (physicsManager, x, y, width, height, maxObjects, maxLevels, level) {
  20015. this.physicsManager = physicsManager;
  20016. this.ID = physicsManager.quadTreeID;
  20017. physicsManager.quadTreeID++;
  20018. this.maxObjects = maxObjects || 10;
  20019. this.maxLevels = maxLevels || 4;
  20020. this.level = level || 0;
  20021. this.bounds = {
  20022. x: Math.round(x),
  20023. y: Math.round(y),
  20024. width: width,
  20025. height: height,
  20026. subWidth: Math.floor(width / 2),
  20027. subHeight: Math.floor(height / 2),
  20028. right: Math.round(x) + Math.floor(width / 2),
  20029. bottom: Math.round(y) + Math.floor(height / 2)
  20030. };
  20031. this.objects = [];
  20032. this.nodes = [];
  20033. };
  20034. Phaser.QuadTree.prototype = {
  20035. /*
  20036. * Split the node into 4 subnodes
  20037. *
  20038. * @method Phaser.QuadTree#split
  20039. */
  20040. split: function() {
  20041. this.level++;
  20042. // top right node
  20043. this.nodes[0] = new Phaser.QuadTree(this.physicsManager, this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
  20044. // top left node
  20045. this.nodes[1] = new Phaser.QuadTree(this.physicsManager, this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
  20046. // bottom left node
  20047. this.nodes[2] = new Phaser.QuadTree(this.physicsManager, this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
  20048. // bottom right node
  20049. this.nodes[3] = new Phaser.QuadTree(this.physicsManager, this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
  20050. },
  20051. /*
  20052. * Insert the object into the node. If the node
  20053. * exceeds the capacity, it will split and add all
  20054. * objects to their corresponding subnodes.
  20055. *
  20056. * @method Phaser.QuadTree#insert
  20057. * @param {object} body - Description.
  20058. */
  20059. insert: function (body) {
  20060. var i = 0;
  20061. var index;
  20062. // if we have subnodes ...
  20063. if (this.nodes[0] != null)
  20064. {
  20065. index = this.getIndex(body);
  20066. if (index !== -1)
  20067. {
  20068. this.nodes[index].insert(body);
  20069. return;
  20070. }
  20071. }
  20072. this.objects.push(body);
  20073. if (this.objects.length > this.maxObjects && this.level < this.maxLevels)
  20074. {
  20075. // Split if we don't already have subnodes
  20076. if (this.nodes[0] == null)
  20077. {
  20078. this.split();
  20079. }
  20080. // Add objects to subnodes
  20081. while (i < this.objects.length)
  20082. {
  20083. index = this.getIndex(this.objects[i]);
  20084. if (index !== -1)
  20085. {
  20086. // this is expensive - see what we can do about it
  20087. this.nodes[index].insert(this.objects.splice(i, 1)[0]);
  20088. }
  20089. else
  20090. {
  20091. i++;
  20092. }
  20093. }
  20094. }
  20095. },
  20096. /*
  20097. * Determine which node the object belongs to.
  20098. *
  20099. * @method Phaser.QuadTree#getIndex
  20100. * @param {object} rect - Description.
  20101. * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node.
  20102. */
  20103. getIndex: function (rect) {
  20104. // default is that rect doesn't fit, i.e. it straddles the internal quadrants
  20105. var index = -1;
  20106. if (rect.x < this.bounds.right && rect.right < this.bounds.right)
  20107. {
  20108. if ((rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom))
  20109. {
  20110. // rect fits within the top-left quadrant of this quadtree
  20111. index = 1;
  20112. }
  20113. else if ((rect.y > this.bounds.bottom))
  20114. {
  20115. // rect fits within the bottom-left quadrant of this quadtree
  20116. index = 2;
  20117. }
  20118. }
  20119. else if (rect.x > this.bounds.right)
  20120. {
  20121. // rect can completely fit within the right quadrants
  20122. if ((rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom))
  20123. {
  20124. // rect fits within the top-right quadrant of this quadtree
  20125. index = 0;
  20126. }
  20127. else if ((rect.y > this.bounds.bottom))
  20128. {
  20129. // rect fits within the bottom-right quadrant of this quadtree
  20130. index = 3;
  20131. }
  20132. }
  20133. return index;
  20134. },
  20135. /*
  20136. * Return all objects that could collide with the given object.
  20137. *
  20138. * @method Phaser.QuadTree#retrieve
  20139. * @param {object} rect - Description.
  20140. * @Return {array} - Array with all detected objects.
  20141. */
  20142. retrieve: function (sprite) {
  20143. var returnObjects = this.objects;
  20144. sprite.body.quadTreeIndex = this.getIndex(sprite.body);
  20145. // Temp store for the node IDs this sprite is in, we can use this for fast elimination later
  20146. sprite.body.quadTreeIDs.push(this.ID);
  20147. if (this.nodes[0])
  20148. {
  20149. // if rect fits into a subnode ..
  20150. if (sprite.body.quadTreeIndex !== -1)
  20151. {
  20152. returnObjects = returnObjects.concat(this.nodes[sprite.body.quadTreeIndex].retrieve(sprite));
  20153. }
  20154. else
  20155. {
  20156. // if rect does not fit into a subnode, check it against all subnodes (unrolled for speed)
  20157. returnObjects = returnObjects.concat(this.nodes[0].retrieve(sprite));
  20158. returnObjects = returnObjects.concat(this.nodes[1].retrieve(sprite));
  20159. returnObjects = returnObjects.concat(this.nodes[2].retrieve(sprite));
  20160. returnObjects = returnObjects.concat(this.nodes[3].retrieve(sprite));
  20161. }
  20162. }
  20163. return returnObjects;
  20164. },
  20165. /*
  20166. * Clear the quadtree.
  20167. * @method Phaser.QuadTree#clear
  20168. */
  20169. clear: function () {
  20170. this.objects = [];
  20171. for (var i = 0, len = this.nodes.length; i < len; i++)
  20172. {
  20173. // if (typeof this.nodes[i] !== 'undefined')
  20174. if (this.nodes[i])
  20175. {
  20176. this.nodes[i].clear();
  20177. delete this.nodes[i];
  20178. }
  20179. }
  20180. }
  20181. };
  20182. /**
  20183. * @author Richard Davey <rich@photonstorm.com>
  20184. * @copyright 2013 Photon Storm Ltd.
  20185. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20186. */
  20187. /**
  20188. * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created.
  20189. * @class Circle
  20190. * @classdesc Phaser - Circle
  20191. * @constructor
  20192. * @param {number} [x] The x coordinate of the center of the circle.
  20193. * @param {number} [y] The y coordinate of the center of the circle.
  20194. * @param {number} [diameter] The diameter of the circle.
  20195. * @return {Phaser.Circle} This circle object
  20196. */
  20197. Phaser.Circle = function (x, y, diameter) {
  20198. x = x || 0;
  20199. y = y || 0;
  20200. diameter = diameter || 0;
  20201. /**
  20202. * @property {number} x - The x coordinate of the center of the circle.
  20203. */
  20204. this.x = x;
  20205. /**
  20206. * @property {number} y - The y coordinate of the center of the circle.
  20207. */
  20208. this.y = y;
  20209. /**
  20210. * @property {number} _diameter - The diameter of the circle.
  20211. * @private
  20212. */
  20213. this._diameter = diameter;
  20214. if (diameter > 0)
  20215. {
  20216. /**
  20217. * @property {number} _radius - The radius of the circle.
  20218. * @private
  20219. */
  20220. this._radius = diameter * 0.5;
  20221. }
  20222. else
  20223. {
  20224. this._radius = 0;
  20225. }
  20226. };
  20227. Phaser.Circle.prototype = {
  20228. /**
  20229. * The circumference of the circle.
  20230. * @method Phaser.Circle#circumference
  20231. * @return {number}
  20232. */
  20233. circumference: function () {
  20234. return 2 * (Math.PI * this._radius);
  20235. },
  20236. /**
  20237. * Sets the members of Circle to the specified values.
  20238. * @method Phaser.Circle#setTo
  20239. * @param {number} x - The x coordinate of the center of the circle.
  20240. * @param {number} y - The y coordinate of the center of the circle.
  20241. * @param {number} diameter - The diameter of the circle in pixels.
  20242. * @return {Circle} This circle object.
  20243. */
  20244. setTo: function (x, y, diameter) {
  20245. this.x = x;
  20246. this.y = y;
  20247. this._diameter = diameter;
  20248. this._radius = diameter * 0.5;
  20249. return this;
  20250. },
  20251. /**
  20252. * Copies the x, y and diameter properties from any given object to this Circle.
  20253. * @method Phaser.Circle#copyFrom
  20254. * @param {any} source - The object to copy from.
  20255. * @return {Circle} This Circle object.
  20256. */
  20257. copyFrom: function (source) {
  20258. return this.setTo(source.x, source.y, source.diameter);
  20259. },
  20260. /**
  20261. * Copies the x, y and diameter properties from this Circle to any given object.
  20262. * @method Phaser.Circle#copyTo
  20263. * @param {any} dest - The object to copy to.
  20264. * @return {Object} This dest object.
  20265. */
  20266. copyTo: function(dest) {
  20267. dest.x = this.x;
  20268. dest.y = this.y;
  20269. dest.diameter = this._diameter;
  20270. return dest;
  20271. },
  20272. /**
  20273. * Returns the distance from the center of the Circle object to the given object
  20274. * (can be Circle, Point or anything with x/y properties)
  20275. * @method Phaser.Circle#distance
  20276. * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
  20277. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  20278. * @return {number} The distance between this Point object and the destination Point object.
  20279. */
  20280. distance: function (dest, round) {
  20281. if (typeof round === "undefined") { round = false }
  20282. if (round)
  20283. {
  20284. return Phaser.Math.distanceRound(this.x, this.y, dest.x, dest.y);
  20285. }
  20286. else
  20287. {
  20288. return Phaser.Math.distance(this.x, this.y, dest.x, dest.y);
  20289. }
  20290. },
  20291. /**
  20292. * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object.
  20293. * @method Phaser.Circle#clone
  20294. * @param {Phaser.Circle} out - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned.
  20295. * @return {Phaser.Circle} The cloned Circle object.
  20296. */
  20297. clone: function(out) {
  20298. if (typeof out === "undefined") { out = new Phaser.Circle(); }
  20299. return out.setTo(this.x, this.y, this.diameter);
  20300. },
  20301. /**
  20302. * Return true if the given x/y coordinates are within this Circle object.
  20303. * @method Phaser.Circle#contains
  20304. * @param {number} x - The X value of the coordinate to test.
  20305. * @param {number} y - The Y value of the coordinate to test.
  20306. * @return {boolean} True if the coordinates are within this circle, otherwise false.
  20307. */
  20308. contains: function (x, y) {
  20309. return Phaser.Circle.contains(this, x, y);
  20310. },
  20311. /**
  20312. * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
  20313. * @method Phaser.Circle#circumferencePoint
  20314. * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
  20315. * @param {boolean} asDegrees - Is the given angle in radians (false) or degrees (true)?
  20316. * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
  20317. * @return {Phaser.Point} The Point object holding the result.
  20318. */
  20319. circumferencePoint: function (angle, asDegrees, out) {
  20320. return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out);
  20321. },
  20322. /**
  20323. * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts.
  20324. * @method Phaser.Circle#offset
  20325. * @param {number} dx - Moves the x value of the Circle object by this amount.
  20326. * @param {number} dy - Moves the y value of the Circle object by this amount.
  20327. * @return {Circle} This Circle object.
  20328. */
  20329. offset: function (dx, dy) {
  20330. this.x += dx;
  20331. this.y += dy;
  20332. return this;
  20333. },
  20334. /**
  20335. * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter.
  20336. * @method Phaser.Circle#offsetPoint
  20337. * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties).
  20338. * @return {Circle} This Circle object.
  20339. */
  20340. offsetPoint: function (point) {
  20341. return this.offset(point.x, point.y);
  20342. },
  20343. /**
  20344. * Returns a string representation of this object.
  20345. * @method Phaser.Circle#toString
  20346. * @return {string} a string representation of the instance.
  20347. */
  20348. toString: function () {
  20349. return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]";
  20350. }
  20351. };
  20352. /**
  20353. * The largest distance between any two points on the circle. The same as the radius * 2.
  20354. * @name Phaser.Circle#diameter
  20355. * @property {number} diameter - Gets or sets the diameter of the circle.
  20356. */
  20357. Object.defineProperty(Phaser.Circle.prototype, "diameter", {
  20358. get: function () {
  20359. return this._diameter;
  20360. },
  20361. set: function (value) {
  20362. if (value > 0) {
  20363. this._diameter = value;
  20364. this._radius = value * 0.5;
  20365. }
  20366. }
  20367. });
  20368. /**
  20369. * The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter.
  20370. * @name Phaser.Circle#radius
  20371. * @property {number} radius - Gets or sets the radius of the circle.
  20372. */
  20373. Object.defineProperty(Phaser.Circle.prototype, "radius", {
  20374. get: function () {
  20375. return this._radius;
  20376. },
  20377. set: function (value) {
  20378. if (value > 0) {
  20379. this._radius = value;
  20380. this._diameter = value * 2;
  20381. }
  20382. }
  20383. });
  20384. /**
  20385. * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
  20386. * @name Phaser.Circle#left
  20387. * @propety {number} left - Gets or sets the value of the leftmost point of the circle.
  20388. */
  20389. Object.defineProperty(Phaser.Circle.prototype, "left", {
  20390. get: function () {
  20391. return this.x - this._radius;
  20392. },
  20393. set: function (value) {
  20394. if (value > this.x) {
  20395. this._radius = 0;
  20396. this._diameter = 0;
  20397. } else {
  20398. this.radius = this.x - value;
  20399. }
  20400. }
  20401. });
  20402. /**
  20403. * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
  20404. * @name Phaser.Circle#right
  20405. * @property {number} right - Gets or sets the value of the rightmost point of the circle.
  20406. */
  20407. Object.defineProperty(Phaser.Circle.prototype, "right", {
  20408. get: function () {
  20409. return this.x + this._radius;
  20410. },
  20411. set: function (value) {
  20412. if (value < this.x) {
  20413. this._radius = 0;
  20414. this._diameter = 0;
  20415. } else {
  20416. this.radius = value - this.x;
  20417. }
  20418. }
  20419. });
  20420. /**
  20421. * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter.
  20422. * @name Phaser.Circle#top
  20423. * @property {number} top - Gets or sets the top of the circle.
  20424. */
  20425. Object.defineProperty(Phaser.Circle.prototype, "top", {
  20426. get: function () {
  20427. return this.y - this._radius;
  20428. },
  20429. set: function (value) {
  20430. if (value > this.y) {
  20431. this._radius = 0;
  20432. this._diameter = 0;
  20433. } else {
  20434. this.radius = this.y - value;
  20435. }
  20436. }
  20437. });
  20438. /**
  20439. * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter.
  20440. * @name Phaser.Circle#bottom
  20441. * @property {number} bottom - Gets or sets the bottom of the circle.
  20442. */
  20443. Object.defineProperty(Phaser.Circle.prototype, "bottom", {
  20444. get: function () {
  20445. return this.y + this._radius;
  20446. },
  20447. set: function (value) {
  20448. if (value < this.y) {
  20449. this._radius = 0;
  20450. this._diameter = 0;
  20451. } else {
  20452. this.radius = value - this.y;
  20453. }
  20454. }
  20455. });
  20456. /**
  20457. * The area of this Circle.
  20458. * @name Phaser.Circle#area
  20459. * @property {number} area - The area of this circle.
  20460. * @readonly
  20461. */
  20462. Object.defineProperty(Phaser.Circle.prototype, "area", {
  20463. get: function () {
  20464. if (this._radius > 0) {
  20465. return Math.PI * this._radius * this._radius;
  20466. } else {
  20467. return 0;
  20468. }
  20469. }
  20470. });
  20471. /**
  20472. * Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false.
  20473. * If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0.
  20474. * @name Phaser.Circle#empty
  20475. * @property {boolean} empty - Gets or sets the empty state of the circle.
  20476. */
  20477. Object.defineProperty(Phaser.Circle.prototype, "empty", {
  20478. get: function () {
  20479. return (this._diameter === 0);
  20480. },
  20481. set: function (value) {
  20482. if (value === true)
  20483. {
  20484. this.setTo(0, 0, 0);
  20485. }
  20486. }
  20487. });
  20488. /**
  20489. * Return true if the given x/y coordinates are within the Circle object.
  20490. * @method Phaser.Circle.contains
  20491. * @param {Phaser.Circle} a - The Circle to be checked.
  20492. * @param {number} x - The X value of the coordinate to test.
  20493. * @param {number} y - The Y value of the coordinate to test.
  20494. * @return {boolean} True if the coordinates are within this circle, otherwise false.
  20495. */
  20496. Phaser.Circle.contains = function (a, x, y) {
  20497. // Check if x/y are within the bounds first
  20498. if (x >= a.left && x <= a.right && y >= a.top && y <= a.bottom) {
  20499. var dx = (a.x - x) * (a.x - x);
  20500. var dy = (a.y - y) * (a.y - y);
  20501. return (dx + dy) <= (a.radius * a.radius);
  20502. }
  20503. return false;
  20504. };
  20505. /**
  20506. * Determines whether the two Circle objects match. This method compares the x, y and diameter properties.
  20507. * @method Phaser.Circle.equals
  20508. * @param {Phaser.Circle} a - The first Circle object.
  20509. * @param {Phaser.Circle} b - The second Circle object.
  20510. * @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false.
  20511. */
  20512. Phaser.Circle.equals = function (a, b) {
  20513. return (a.x == b.x && a.y == b.y && a.diameter == b.diameter);
  20514. };
  20515. /**
  20516. * Determines whether the two Circle objects intersect.
  20517. * This method checks the radius distances between the two Circle objects to see if they intersect.
  20518. * @method Phaser.Circle.intersects
  20519. * @param {Phaser.Circle} a - The first Circle object.
  20520. * @param {Phaser.Circle} b - The second Circle object.
  20521. * @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false.
  20522. */
  20523. Phaser.Circle.intersects = function (a, b) {
  20524. return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius));
  20525. };
  20526. /**
  20527. * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
  20528. * @method Phaser.Circle.circumferencePoint
  20529. * @param {Phaser.Circle} a - The first Circle object.
  20530. * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
  20531. * @param {boolean} asDegrees - Is the given angle in radians (false) or degrees (true)?
  20532. * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
  20533. * @return {Phaser.Point} The Point object holding the result.
  20534. */
  20535. Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) {
  20536. if (typeof asDegrees === "undefined") { asDegrees = false; }
  20537. if (typeof out === "undefined") { out = new Phaser.Point(); }
  20538. if (asDegrees === true) {
  20539. angle = Phaser.Math.radToDeg(angle);
  20540. }
  20541. out.x = a.x + a.radius * Math.cos(angle);
  20542. out.y = a.y + a.radius * Math.sin(angle);
  20543. return out;
  20544. };
  20545. /**
  20546. * Checks if the given Circle and Rectangle objects intersect.
  20547. * @method Phaser.Circle.intersectsRectangle
  20548. * @param {Phaser.Circle} c - The Circle object to test.
  20549. * @param {Phaser.Rectangle} r - The Rectangle object to test.
  20550. * @return {boolean} True if the two objects intersect, otherwise false.
  20551. */
  20552. Phaser.Circle.intersectsRectangle = function (c, r) {
  20553. var cx = Math.abs(c.x - r.x - r.halfWidth);
  20554. var xDist = r.halfWidth + c.radius;
  20555. if (cx > xDist) {
  20556. return false;
  20557. }
  20558. var cy = Math.abs(c.y - r.y - r.halfHeight);
  20559. var yDist = r.halfHeight + c.radius;
  20560. if (cy > yDist) {
  20561. return false;
  20562. }
  20563. if (cx <= r.halfWidth || cy <= r.halfHeight) {
  20564. return true;
  20565. }
  20566. var xCornerDist = cx - r.halfWidth;
  20567. var yCornerDist = cy - r.halfHeight;
  20568. var xCornerDistSq = xCornerDist * xCornerDist;
  20569. var yCornerDistSq = yCornerDist * yCornerDist;
  20570. var maxCornerDistSq = c.radius * c.radius;
  20571. return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
  20572. };
  20573. /**
  20574. * @author Richard Davey <rich@photonstorm.com>
  20575. * @copyright 2013 Photon Storm Ltd.
  20576. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20577. */
  20578. /**
  20579. * Creates a new Point. If you pass no parameters a Point is created set to (0,0).
  20580. * @class Phaser.Point
  20581. * @classdesc The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
  20582. * @constructor
  20583. * @param {number} x The horizontal position of this Point (default 0)
  20584. * @param {number} y The vertical position of this Point (default 0)
  20585. */
  20586. Phaser.Point = function (x, y) {
  20587. x = x || 0;
  20588. y = y || 0;
  20589. /**
  20590. * @property {number} x - The x coordinate of the point.
  20591. */
  20592. this.x = x;
  20593. /**
  20594. * @property {number} y - The y coordinate of the point.
  20595. */
  20596. this.y = y;
  20597. };
  20598. Phaser.Point.prototype = {
  20599. /**
  20600. * Copies the x and y properties from any given object to this Point.
  20601. * @method Phaser.Point#copyFrom
  20602. * @param {any} source - The object to copy from.
  20603. * @return {Point} This Point object.
  20604. */
  20605. copyFrom: function (source) {
  20606. return this.setTo(source.x, source.y);
  20607. },
  20608. /**
  20609. * Inverts the x and y values of this Point
  20610. * @method Phaser.Point#invert
  20611. * @return {Point} This Point object.
  20612. */
  20613. invert: function () {
  20614. return this.setTo(this.y, this.x);
  20615. },
  20616. /**
  20617. * Sets the x and y values of this Point object to the given coordinates.
  20618. * @method Phaser.Point#setTo
  20619. * @param {number} x - The horizontal position of this point.
  20620. * @param {number} y - The vertical position of this point.
  20621. * @return {Point} This Point object. Useful for chaining method calls.
  20622. */
  20623. setTo: function (x, y) {
  20624. this.x = x;
  20625. this.y = y;
  20626. return this;
  20627. },
  20628. /**
  20629. * Adds the given x and y values to this Point.
  20630. * @method Phaser.Point#add
  20631. * @param {number} x - The value to add to Point.x.
  20632. * @param {number} y - The value to add to Point.y.
  20633. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  20634. */
  20635. add: function (x, y) {
  20636. this.x += x;
  20637. this.y += y;
  20638. return this;
  20639. },
  20640. /**
  20641. * Subtracts the given x and y values from this Point.
  20642. * @method Phaser.Point#subtract
  20643. * @param {number} x - The value to subtract from Point.x.
  20644. * @param {number} y - The value to subtract from Point.y.
  20645. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  20646. */
  20647. subtract: function (x, y) {
  20648. this.x -= x;
  20649. this.y -= y;
  20650. return this;
  20651. },
  20652. /**
  20653. * Multiplies Point.x and Point.y by the given x and y values.
  20654. * @method Phaser.Point#multiply
  20655. * @param {number} x - The value to multiply Point.x by.
  20656. * @param {number} y - The value to multiply Point.x by.
  20657. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  20658. */
  20659. multiply: function (x, y) {
  20660. this.x *= x;
  20661. this.y *= y;
  20662. return this;
  20663. },
  20664. /**
  20665. * Divides Point.x and Point.y by the given x and y values.
  20666. * @method Phaser.Point#divide
  20667. * @param {number} x - The value to divide Point.x by.
  20668. * @param {number} y - The value to divide Point.x by.
  20669. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  20670. */
  20671. divide: function (x, y) {
  20672. this.x /= x;
  20673. this.y /= y;
  20674. return this;
  20675. },
  20676. /**
  20677. * Clamps the x value of this Point to be between the given min and max.
  20678. * @method Phaser.Point#clampX
  20679. * @param {number} min - The minimum value to clamp this Point to.
  20680. * @param {number} max - The maximum value to clamp this Point to.
  20681. * @return {Phaser.Point} This Point object.
  20682. */
  20683. clampX: function (min, max) {
  20684. this.x = Phaser.Math.clamp(this.x, min, max);
  20685. return this;
  20686. },
  20687. /**
  20688. * Clamps the y value of this Point to be between the given min and max
  20689. * @method Phaser.Point#clampY
  20690. * @param {number} min - The minimum value to clamp this Point to.
  20691. * @param {number} max - The maximum value to clamp this Point to.
  20692. * @return {Phaser.Point} This Point object.
  20693. */
  20694. clampY: function (min, max) {
  20695. this.y = Phaser.Math.clamp(this.y, min, max);
  20696. return this;
  20697. },
  20698. /**
  20699. * Clamps this Point object values to be between the given min and max.
  20700. * @method Phaser.Point#clamp
  20701. * @param {number} min - The minimum value to clamp this Point to.
  20702. * @param {number} max - The maximum value to clamp this Point to.
  20703. * @return {Phaser.Point} This Point object.
  20704. */
  20705. clamp: function (min, max) {
  20706. this.x = Phaser.Math.clamp(this.x, min, max);
  20707. this.y = Phaser.Math.clamp(this.y, min, max);
  20708. return this;
  20709. },
  20710. /**
  20711. * Creates a copy of the given Point.
  20712. * @method Phaser.Point#clone
  20713. * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned.
  20714. * @return {Phaser.Point} The new Point object.
  20715. */
  20716. clone: function (output) {
  20717. if (typeof output === "undefined") { output = new Phaser.Point(); }
  20718. return output.setTo(this.x, this.y);
  20719. },
  20720. /**
  20721. * Copies the x and y properties from this Point to any given object.
  20722. * @method Phaser.Point#copyTo
  20723. * @param {any} dest - The object to copy to.
  20724. * @return {Object} The dest object.
  20725. */
  20726. copyTo: function(dest) {
  20727. dest.x = this.x;
  20728. dest.y = this.y;
  20729. return dest;
  20730. },
  20731. /**
  20732. * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties)
  20733. * @method Phaser.Point#distance
  20734. * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
  20735. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  20736. * @return {number} The distance between this Point object and the destination Point object.
  20737. */
  20738. distance: function (dest, round) {
  20739. return Phaser.Point.distance(this, dest, round);
  20740. },
  20741. /**
  20742. * Determines whether the given objects x/y values are equal to this Point object.
  20743. * @method Phaser.Point#equals
  20744. * @param {Phaser.Point} a - The first object to compare.
  20745. * @return {boolean} A value of true if the Points are equal, otherwise false.
  20746. */
  20747. equals: function (a) {
  20748. return (a.x == this.x && a.y == this.y);
  20749. },
  20750. /**
  20751. * Rotates this Point around the x/y coordinates given to the desired angle.
  20752. * @method Phaser.Point#rotate
  20753. * @param {number} x - The x coordinate of the anchor point
  20754. * @param {number} y - The y coordinate of the anchor point
  20755. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
  20756. * @param {boolean} asDegrees - Is the given rotation in radians (false) or degrees (true)?
  20757. * @param {number} [distance] - An optional distance constraint between the Point and the anchor.
  20758. * @return {Phaser.Point} The modified point object.
  20759. */
  20760. rotate: function (x, y, angle, asDegrees, distance) {
  20761. return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance);
  20762. },
  20763. /**
  20764. * Calculates the length of the vector
  20765. * @method Phaser.Point#getMagnitude
  20766. * @return {number} the length of the vector
  20767. */
  20768. getMagnitude: function() {
  20769. return Math.sqrt((this.x * this.x) + (this.y * this.y));
  20770. },
  20771. /**
  20772. * Alters the length of the vector without changing the direction
  20773. * @method Phaser.Point#getMagnitude
  20774. * @param {number} magnitude the desired magnitude of the resulting vector
  20775. * @return {Phaser.Point} the modified original vector
  20776. */
  20777. setMagnitude: function(magnitude) {
  20778. return this.normalize().multiply(magnitude, magnitude);
  20779. },
  20780. /**
  20781. * Alters the vector so that its length is 1, but it retains the same direction
  20782. * @method Phaser.Point#normalize
  20783. * @return {Phaser.Point} the modified original vector
  20784. */
  20785. normalize: function() {
  20786. if(!this.isZero()) {
  20787. var m = this.getMagnitude();
  20788. this.x /= m;
  20789. this.y /= m;
  20790. }
  20791. return this;
  20792. },
  20793. /**
  20794. * Determine if this point is at 0,0
  20795. * @method Phaser.Point#isZero
  20796. * @return {boolean} True if this Point is 0,0, otherwise false
  20797. */
  20798. isZero: function() {
  20799. return (this.x === 0 && this.y === 0);
  20800. },
  20801. /**
  20802. * Returns a string representation of this object.
  20803. * @method Phaser.Point#toString
  20804. * @return {string} A string representation of the instance.
  20805. */
  20806. toString: function () {
  20807. return '[{Point (x=' + this.x + ' y=' + this.y + ')}]';
  20808. }
  20809. };
  20810. /**
  20811. * Adds the coordinates of two points together to create a new point.
  20812. * @method Phaser.Point.add
  20813. * @param {Phaser.Point} a - The first Point object.
  20814. * @param {Phaser.Point} b - The second Point object.
  20815. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  20816. * @return {Phaser.Point} The new Point object.
  20817. */
  20818. Phaser.Point.add = function (a, b, out) {
  20819. if (typeof out === "undefined") { out = new Phaser.Point(); }
  20820. out.x = a.x + b.x;
  20821. out.y = a.y + b.y;
  20822. return out;
  20823. };
  20824. /**
  20825. * Subtracts the coordinates of two points to create a new point.
  20826. * @method Phaser.Point.subtract
  20827. * @param {Phaser.Point} a - The first Point object.
  20828. * @param {Phaser.Point} b - The second Point object.
  20829. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  20830. * @return {Phaser.Point} The new Point object.
  20831. */
  20832. Phaser.Point.subtract = function (a, b, out) {
  20833. if (typeof out === "undefined") { out = new Phaser.Point(); }
  20834. out.x = a.x - b.x;
  20835. out.y = a.y - b.y;
  20836. return out;
  20837. };
  20838. /**
  20839. * Multiplies the coordinates of two points to create a new point.
  20840. * @method Phaser.Point.multiply
  20841. * @param {Phaser.Point} a - The first Point object.
  20842. * @param {Phaser.Point} b - The second Point object.
  20843. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  20844. * @return {Phaser.Point} The new Point object.
  20845. */
  20846. Phaser.Point.multiply = function (a, b, out) {
  20847. if (typeof out === "undefined") { out = new Phaser.Point(); }
  20848. out.x = a.x * b.x;
  20849. out.y = a.y * b.y;
  20850. return out;
  20851. };
  20852. /**
  20853. * Divides the coordinates of two points to create a new point.
  20854. * @method Phaser.Point.divide
  20855. * @param {Phaser.Point} a - The first Point object.
  20856. * @param {Phaser.Point} b - The second Point object.
  20857. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  20858. * @return {Phaser.Point} The new Point object.
  20859. */
  20860. Phaser.Point.divide = function (a, b, out) {
  20861. if (typeof out === "undefined") { out = new Phaser.Point(); }
  20862. out.x = a.x / b.x;
  20863. out.y = a.y / b.y;
  20864. return out;
  20865. };
  20866. /**
  20867. * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values.
  20868. * @method Phaser.Point.equals
  20869. * @param {Phaser.Point} a - The first Point object.
  20870. * @param {Phaser.Point} b - The second Point object.
  20871. * @return {boolean} A value of true if the Points are equal, otherwise false.
  20872. */
  20873. Phaser.Point.equals = function (a, b) {
  20874. return (a.x == b.x && a.y == b.y);
  20875. };
  20876. /**
  20877. * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties).
  20878. * @method Phaser.Point.distance
  20879. * @param {object} a - The target object. Must have visible x and y properties that represent the center of the object.
  20880. * @param {object} b - The target object. Must have visible x and y properties that represent the center of the object.
  20881. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  20882. * @return {number} The distance between this Point object and the destination Point object.
  20883. */
  20884. Phaser.Point.distance = function (a, b, round) {
  20885. if (typeof round === "undefined") { round = false }
  20886. if (round)
  20887. {
  20888. return Phaser.Math.distanceRound(a.x, a.y, b.x, b.y);
  20889. }
  20890. else
  20891. {
  20892. return Phaser.Math.distance(a.x, a.y, b.x, b.y);
  20893. }
  20894. };
  20895. /**
  20896. * Rotates a Point around the x/y coordinates given to the desired angle.
  20897. * @method Phaser.Point.rotate
  20898. * @param {Phaser.Point} a - The Point object to rotate.
  20899. * @param {number} x - The x coordinate of the anchor point
  20900. * @param {number} y - The y coordinate of the anchor point
  20901. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
  20902. * @param {boolean} asDegrees - Is the given rotation in radians (false) or degrees (true)?
  20903. * @param {number} distance - An optional distance constraint between the Point and the anchor.
  20904. * @return {Phaser.Point} The modified point object.
  20905. */
  20906. Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) {
  20907. asDegrees = asDegrees || false;
  20908. distance = distance || null;
  20909. if (asDegrees)
  20910. {
  20911. angle = Phaser.Math.degToRad(angle);
  20912. }
  20913. // Get distance from origin (cx/cy) to this point
  20914. if (distance === null)
  20915. {
  20916. distance = Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y)));
  20917. }
  20918. return a.setTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle));
  20919. };
  20920. /**
  20921. * @author Richard Davey <rich@photonstorm.com>
  20922. * @copyright 2013 Photon Storm Ltd.
  20923. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20924. */
  20925. /**
  20926. * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created.
  20927. *
  20928. * @class Phaser.Rectangle
  20929. * @constructor
  20930. * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
  20931. * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
  20932. * @param {number} width - The width of the Rectangle.
  20933. * @param {number} height - The height of the Rectangle.
  20934. * @return {Rectangle} This Rectangle object.
  20935. */
  20936. Phaser.Rectangle = function (x, y, width, height) {
  20937. x = x || 0;
  20938. y = y || 0;
  20939. width = width || 0;
  20940. height = height || 0;
  20941. /**
  20942. * @property {number} x - The x coordinate of the top-left corner of the Rectangle.
  20943. */
  20944. this.x = x;
  20945. /**
  20946. * @property {number} y - The y coordinate of the top-left corner of the Rectangle.
  20947. */
  20948. this.y = y;
  20949. /**
  20950. * @property {number} width - The width of the Rectangle.
  20951. */
  20952. this.width = width;
  20953. /**
  20954. * @property {number} height - The height of the Rectangle.
  20955. */
  20956. this.height = height;
  20957. };
  20958. Phaser.Rectangle.prototype = {
  20959. /**
  20960. * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts.
  20961. * @method Phaser.Rectangle#offset
  20962. * @param {number} dx - Moves the x value of the Rectangle object by this amount.
  20963. * @param {number} dy - Moves the y value of the Rectangle object by this amount.
  20964. * @return {Rectangle} This Rectangle object.
  20965. */
  20966. offset: function (dx, dy) {
  20967. this.x += dx;
  20968. this.y += dy;
  20969. return this;
  20970. },
  20971. /**
  20972. * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter.
  20973. * @method Phaser.Rectangle#offsetPoint
  20974. * @param {Point} point - A Point object to use to offset this Rectangle object.
  20975. * @return {Rectangle} This Rectangle object.
  20976. */
  20977. offsetPoint: function (point) {
  20978. return this.offset(point.x, point.y);
  20979. },
  20980. /**
  20981. * Sets the members of Rectangle to the specified values.
  20982. * @method Phaser.Rectangle#setTo
  20983. * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
  20984. * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
  20985. * @param {number} width - The width of the Rectangle in pixels.
  20986. * @param {number} height - The height of the Rectangle in pixels.
  20987. * @return {Rectangle} This Rectangle object
  20988. */
  20989. setTo: function (x, y, width, height) {
  20990. this.x = x;
  20991. this.y = y;
  20992. this.width = width;
  20993. this.height = height;
  20994. return this;
  20995. },
  20996. /**
  20997. * Runs Math.floor() on both the x and y values of this Rectangle.
  20998. * @method Phaser.Rectangle#floor
  20999. */
  21000. floor: function () {
  21001. this.x = Math.floor(this.x);
  21002. this.y = Math.floor(this.y);
  21003. },
  21004. /**
  21005. * Runs Math.floor() on the x, y, width and height values of this Rectangle.
  21006. * @method Phaser.Rectangle#floorAll
  21007. */
  21008. floorAll: function () {
  21009. this.x = Math.floor(this.x);
  21010. this.y = Math.floor(this.y);
  21011. this.width = Math.floor(this.width);
  21012. this.height = Math.floor(this.height);
  21013. },
  21014. /**
  21015. * Copies the x, y, width and height properties from any given object to this Rectangle.
  21016. * @method Phaser.Rectangle#copyFrom
  21017. * @param {any} source - The object to copy from.
  21018. * @return {Rectangle} This Rectangle object.
  21019. */
  21020. copyFrom: function (source) {
  21021. return this.setTo(source.x, source.y, source.width, source.height);
  21022. },
  21023. /**
  21024. * Copies the x, y, width and height properties from this Rectangle to any given object.
  21025. * @method Phaser.Rectangle#copyTo
  21026. * @param {any} source - The object to copy to.
  21027. * @return {object} This object.
  21028. */
  21029. copyTo: function (dest) {
  21030. dest.x = this.x;
  21031. dest.y = this.y;
  21032. dest.width = this.width;
  21033. dest.height = this.height;
  21034. return dest;
  21035. },
  21036. /**
  21037. * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
  21038. * @method Phaser.Rectangle#inflate
  21039. * @param {number} dx - The amount to be added to the left side of the Rectangle.
  21040. * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
  21041. * @return {Phaser.Rectangle} This Rectangle object.
  21042. */
  21043. inflate: function (dx, dy) {
  21044. return Phaser.Rectangle.inflate(this, dx, dy);
  21045. },
  21046. /**
  21047. * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
  21048. * @method Phaser.Rectangle#size
  21049. * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
  21050. * @return {Phaser.Point} The size of the Rectangle object.
  21051. */
  21052. size: function (output) {
  21053. return Phaser.Rectangle.size(this, output);
  21054. },
  21055. /**
  21056. * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
  21057. * @method Phaser.Rectangle#clone
  21058. * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
  21059. * @return {Phaser.Rectangle}
  21060. */
  21061. clone: function (output) {
  21062. return Phaser.Rectangle.clone(this, output);
  21063. },
  21064. /**
  21065. * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
  21066. * @method Phaser.Rectangle#contains
  21067. * @param {number} x - The x coordinate of the point to test.
  21068. * @param {number} y - The y coordinate of the point to test.
  21069. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  21070. */
  21071. contains: function (x, y) {
  21072. return Phaser.Rectangle.contains(this, x, y);
  21073. },
  21074. /**
  21075. * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
  21076. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
  21077. * @method Phaser.Rectangle#containsRect
  21078. * @param {Phaser.Rectangle} b - The second Rectangle object.
  21079. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  21080. */
  21081. containsRect: function (b) {
  21082. return Phaser.Rectangle.containsRect(this, b);
  21083. },
  21084. /**
  21085. * Determines whether the two Rectangles are equal.
  21086. * This method compares the x, y, width and height properties of each Rectangle.
  21087. * @method Phaser.Rectangle#equals
  21088. * @param {Phaser.Rectangle} b - The second Rectangle object.
  21089. * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false.
  21090. */
  21091. equals: function (b) {
  21092. return Phaser.Rectangle.equals(this, b);
  21093. },
  21094. /**
  21095. * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0.
  21096. * @method Phaser.Rectangle#intersection
  21097. * @param {Phaser.Rectangle} b - The second Rectangle object.
  21098. * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
  21099. * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0.
  21100. */
  21101. intersection: function (b, out) {
  21102. return Phaser.Rectangle.intersection(this, b, out);
  21103. },
  21104. /**
  21105. * Determines whether the two Rectangles intersect with each other.
  21106. * This method checks the x, y, width, and height properties of the Rectangles.
  21107. * @method Phaser.Rectangle#intersects
  21108. * @param {Phaser.Rectangle} b - The second Rectangle object.
  21109. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0.
  21110. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
  21111. */
  21112. intersects: function (b, tolerance) {
  21113. return Phaser.Rectangle.intersects(this, b, tolerance);
  21114. },
  21115. /**
  21116. * Determines whether the object specified intersects (overlaps) with the given values.
  21117. * @method Phaser.Rectangle#intersectsRaw
  21118. * @param {number} left - Description.
  21119. * @param {number} right - Description.
  21120. * @param {number} top - Description.
  21121. * @param {number} bottomt - Description.
  21122. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
  21123. * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
  21124. */
  21125. intersectsRaw: function (left, right, top, bottom, tolerance) {
  21126. return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance);
  21127. },
  21128. /**
  21129. * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
  21130. * @method Phaser.Rectangle#union
  21131. * @param {Phaser.Rectangle} b - The second Rectangle object.
  21132. * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
  21133. * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
  21134. */
  21135. union: function (b, out) {
  21136. return Phaser.Rectangle.union(this, b, out);
  21137. },
  21138. /**
  21139. * Returns a string representation of this object.
  21140. * @method Phaser.Rectangle#toString
  21141. * @return {string} A string representation of the instance.
  21142. */
  21143. toString: function () {
  21144. return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]";
  21145. }
  21146. };
  21147. /**
  21148. * @name Phaser.Rectangle#halfWidth
  21149. * @property {number} halfWidth - Half of the width of the Rectangle.
  21150. * @readonly
  21151. */
  21152. Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", {
  21153. get: function () {
  21154. return Math.round(this.width / 2);
  21155. }
  21156. });
  21157. /**
  21158. * @name Phaser.Rectangle#halfHeight
  21159. * @property {number} halfHeight - Half of the height of the Rectangle.
  21160. * @readonly
  21161. */
  21162. Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", {
  21163. get: function () {
  21164. return Math.round(this.height / 2);
  21165. }
  21166. });
  21167. /**
  21168. * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property.
  21169. * @name Phaser.Rectangle#bottom
  21170. * @property {number} bottom - The sum of the y and height properties.
  21171. */
  21172. Object.defineProperty(Phaser.Rectangle.prototype, "bottom", {
  21173. get: function () {
  21174. return this.y + this.height;
  21175. },
  21176. set: function (value) {
  21177. if (value <= this.y) {
  21178. this.height = 0;
  21179. } else {
  21180. this.height = (this.y - value);
  21181. }
  21182. }
  21183. });
  21184. /**
  21185. * The location of the Rectangles bottom right corner as a Point object.
  21186. * @name Phaser.Rectangle#bottom
  21187. * @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object.
  21188. */
  21189. Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", {
  21190. get: function () {
  21191. return new Phaser.Point(this.right, this.bottom);
  21192. },
  21193. set: function (value) {
  21194. this.right = value.x;
  21195. this.bottom = value.y;
  21196. }
  21197. });
  21198. /**
  21199. * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property.
  21200. * @name Phaser.Rectangle#left
  21201. * @property {number} left - The x coordinate of the left of the Rectangle.
  21202. */
  21203. Object.defineProperty(Phaser.Rectangle.prototype, "left", {
  21204. get: function () {
  21205. return this.x;
  21206. },
  21207. set: function (value) {
  21208. if (value >= this.right) {
  21209. this.width = 0;
  21210. } else {
  21211. this.width = this.right - value;
  21212. }
  21213. this.x = value;
  21214. }
  21215. });
  21216. /**
  21217. * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property.
  21218. * @name Phaser.Rectangle#right
  21219. * @property {number} right - The sum of the x and width properties.
  21220. */
  21221. Object.defineProperty(Phaser.Rectangle.prototype, "right", {
  21222. get: function () {
  21223. return this.x + this.width;
  21224. },
  21225. set: function (value) {
  21226. if (value <= this.x) {
  21227. this.width = 0;
  21228. } else {
  21229. this.width = this.x + value;
  21230. }
  21231. }
  21232. });
  21233. /**
  21234. * The volume of the Rectangle derived from width * height.
  21235. * @name Phaser.Rectangle#volume
  21236. * @property {number} volume - The volume of the Rectangle derived from width * height.
  21237. * @readonly
  21238. */
  21239. Object.defineProperty(Phaser.Rectangle.prototype, "volume", {
  21240. get: function () {
  21241. return this.width * this.height;
  21242. }
  21243. });
  21244. /**
  21245. * The perimeter size of the Rectangle. This is the sum of all 4 sides.
  21246. * @name Phaser.Rectangle#perimeter
  21247. * @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides.
  21248. * @readonly
  21249. */
  21250. Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", {
  21251. get: function () {
  21252. return (this.width * 2) + (this.height * 2);
  21253. }
  21254. });
  21255. /**
  21256. * The x coordinate of the center of the Rectangle.
  21257. * @name Phaser.Rectangle#centerX
  21258. * @property {number} centerX - The x coordinate of the center of the Rectangle.
  21259. */
  21260. Object.defineProperty(Phaser.Rectangle.prototype, "centerX", {
  21261. get: function () {
  21262. return this.x + this.halfWidth;
  21263. },
  21264. set: function (value) {
  21265. this.x = value - this.halfWidth;
  21266. }
  21267. });
  21268. /**
  21269. * The y coordinate of the center of the Rectangle.
  21270. * @name Phaser.Rectangle#centerY
  21271. * @property {number} centerY - The y coordinate of the center of the Rectangle.
  21272. */
  21273. Object.defineProperty(Phaser.Rectangle.prototype, "centerY", {
  21274. get: function () {
  21275. return this.y + this.halfHeight;
  21276. },
  21277. set: function (value) {
  21278. this.y = value - this.halfHeight;
  21279. }
  21280. });
  21281. /**
  21282. * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties.
  21283. * However it does affect the height property, whereas changing the y value does not affect the height property.
  21284. * @name Phaser.Rectangle#top
  21285. * @property {number} top - The y coordinate of the top of the Rectangle.
  21286. */
  21287. Object.defineProperty(Phaser.Rectangle.prototype, "top", {
  21288. get: function () {
  21289. return this.y;
  21290. },
  21291. set: function (value) {
  21292. if (value >= this.bottom) {
  21293. this.height = 0;
  21294. this.y = value;
  21295. } else {
  21296. this.height = (this.bottom - value);
  21297. }
  21298. }
  21299. });
  21300. /**
  21301. * The location of the Rectangles top left corner as a Point object.
  21302. * @name Phaser.Rectangle#topLeft
  21303. * @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object.
  21304. */
  21305. Object.defineProperty(Phaser.Rectangle.prototype, "topLeft", {
  21306. get: function () {
  21307. return new Phaser.Point(this.x, this.y);
  21308. },
  21309. set: function (value) {
  21310. this.x = value.x;
  21311. this.y = value.y;
  21312. }
  21313. });
  21314. /**
  21315. * Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0.
  21316. * If set to true then all of the Rectangle properties are set to 0.
  21317. * @name Phaser.Rectangle#empty
  21318. * @property {boolean} empty - Gets or sets the Rectangles empty state.
  21319. */
  21320. Object.defineProperty(Phaser.Rectangle.prototype, "empty", {
  21321. get: function () {
  21322. return (!this.width || !this.height);
  21323. },
  21324. set: function (value) {
  21325. if (value === true)
  21326. {
  21327. this.setTo(0, 0, 0, 0);
  21328. }
  21329. }
  21330. });
  21331. /**
  21332. * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
  21333. * @method Phaser.Rectangle.inflate
  21334. * @param {Phaser.Rectangle} a - The Rectangle object.
  21335. * @param {number} dx - The amount to be added to the left side of the Rectangle.
  21336. * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
  21337. * @return {Phaser.Rectangle} This Rectangle object.
  21338. */
  21339. Phaser.Rectangle.inflate = function (a, dx, dy) {
  21340. a.x -= dx;
  21341. a.width += 2 * dx;
  21342. a.y -= dy;
  21343. a.height += 2 * dy;
  21344. return a;
  21345. };
  21346. /**
  21347. * Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter.
  21348. * @method Phaser.Rectangle.inflatePoint
  21349. * @param {Phaser.Rectangle} a - The Rectangle object.
  21350. * @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object.
  21351. * @return {Phaser.Rectangle} The Rectangle object.
  21352. */
  21353. Phaser.Rectangle.inflatePoint = function (a, point) {
  21354. return Phaser.Rectangle.inflate(a, point.x, point.y);
  21355. };
  21356. /**
  21357. * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
  21358. * @method Phaser.Rectangle.size
  21359. * @param {Phaser.Rectangle} a - The Rectangle object.
  21360. * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
  21361. * @return {Phaser.Point} The size of the Rectangle object
  21362. */
  21363. Phaser.Rectangle.size = function (a, output) {
  21364. if (typeof output === "undefined") { output = new Phaser.Point(); }
  21365. return output.setTo(a.width, a.height);
  21366. };
  21367. /**
  21368. * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
  21369. * @method Phaser.Rectangle.clone
  21370. * @param {Phaser.Rectangle} a - The Rectangle object.
  21371. * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
  21372. * @return {Phaser.Rectangle}
  21373. */
  21374. Phaser.Rectangle.clone = function (a, output) {
  21375. if (typeof output === "undefined") { output = new Phaser.Rectangle(); }
  21376. return output.setTo(a.x, a.y, a.width, a.height);
  21377. };
  21378. /**
  21379. * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
  21380. * @method Phaser.Rectangle.contains
  21381. * @param {Phaser.Rectangle} a - The Rectangle object.
  21382. * @param {number} x - The x coordinate of the point to test.
  21383. * @param {number} y - The y coordinate of the point to test.
  21384. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  21385. */
  21386. Phaser.Rectangle.contains = function (a, x, y) {
  21387. return (x >= a.x && x <= a.right && y >= a.y && y <= a.bottom);
  21388. };
  21389. Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) {
  21390. return (x >= rx && x <= (rx + rw) && y >= ry && y <= (ry + rh));
  21391. };
  21392. /**
  21393. * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter.
  21394. * @method Phaser.Rectangle.containsPoint
  21395. * @param {Phaser.Rectangle} a - The Rectangle object.
  21396. * @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values.
  21397. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  21398. */
  21399. Phaser.Rectangle.containsPoint = function (a, point) {
  21400. return Phaser.Rectangle.contains(a, point.x, point.y);
  21401. };
  21402. /**
  21403. * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
  21404. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
  21405. * @method Phaser.Rectangle.containsRect
  21406. * @param {Phaser.Rectangle} a - The first Rectangle object.
  21407. * @param {Phaser.Rectangle} b - The second Rectangle object.
  21408. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  21409. */
  21410. Phaser.Rectangle.containsRect = function (a, b) {
  21411. // If the given rect has a larger volume than this one then it can never contain it
  21412. if (a.volume > b.volume)
  21413. {
  21414. return false;
  21415. }
  21416. return (a.x >= b.x && a.y >= b.y && a.right <= b.right && a.bottom <= b.bottom);
  21417. };
  21418. /**
  21419. * Determines whether the two Rectangles are equal.
  21420. * This method compares the x, y, width and height properties of each Rectangle.
  21421. * @method Phaser.Rectangle.equals
  21422. * @param {Phaser.Rectangle} a - The first Rectangle object.
  21423. * @param {Phaser.Rectangle} b - The second Rectangle object.
  21424. * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false.
  21425. */
  21426. Phaser.Rectangle.equals = function (a, b) {
  21427. return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height);
  21428. };
  21429. /**
  21430. * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0.
  21431. * @method Phaser.Rectangle.intersection
  21432. * @param {Phaser.Rectangle} a - The first Rectangle object.
  21433. * @param {Phaser.Rectangle} b - The second Rectangle object.
  21434. * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
  21435. * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0.
  21436. */
  21437. Phaser.Rectangle.intersection = function (a, b, out) {
  21438. out = out || new Phaser.Rectangle();
  21439. if (Phaser.Rectangle.intersects(a, b))
  21440. {
  21441. out.x = Math.max(a.x, b.x);
  21442. out.y = Math.max(a.y, b.y);
  21443. out.width = Math.min(a.right, b.right) - out.x;
  21444. out.height = Math.min(a.bottom, b.bottom) - out.y;
  21445. }
  21446. return out;
  21447. };
  21448. /**
  21449. * Determines whether the two Rectangles intersect with each other.
  21450. * This method checks the x, y, width, and height properties of the Rectangles.
  21451. * @method Phaser.Rectangle.intersects
  21452. * @param {Phaser.Rectangle} a - The first Rectangle object.
  21453. * @param {Phaser.Rectangle} b - The second Rectangle object.
  21454. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
  21455. */
  21456. Phaser.Rectangle.intersects = function (a, b) {
  21457. return (a.x < b.right && b.x < a.right && a.y < b.bottom && b.y < a.bottom);
  21458. // return (a.x <= b.right && b.x <= a.right && a.y <= b.bottom && b.y <= a.bottom);
  21459. // return (a.left <= b.right && b.left <= a.right && a.top <= b.bottom && b.top <= a.bottom);
  21460. // return !(a.x > b.right + tolerance || a.right < b.x - tolerance || a.y > b.bottom + tolerance || a.bottom < b.y - tolerance);
  21461. };
  21462. /**
  21463. * Determines whether the object specified intersects (overlaps) with the given values.
  21464. * @method Phaser.Rectangle.intersectsRaw
  21465. * @param {number} left - Description.
  21466. * @param {number} right - Description.
  21467. * @param {number} top - Description.
  21468. * @param {number} bottom - Description.
  21469. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
  21470. * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
  21471. */
  21472. Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) {
  21473. if (typeof tolerance === "undefined") { tolerance = 0; }
  21474. return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance);
  21475. };
  21476. /**
  21477. * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
  21478. * @method Phaser.Rectangle.union
  21479. * @param {Phaser.Rectangle} a - The first Rectangle object.
  21480. * @param {Phaser.Rectangle} b - The second Rectangle object.
  21481. * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
  21482. * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
  21483. */
  21484. Phaser.Rectangle.union = function (a, b, out) {
  21485. if (typeof out === "undefined") { out = new Phaser.Rectangle(); }
  21486. return out.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top));
  21487. };
  21488. /**
  21489. * @author Richard Davey <rich@photonstorm.com>
  21490. * @copyright 2013 Photon Storm Ltd.
  21491. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21492. */
  21493. /**
  21494. * Creates a new Polygon. You have to provide a list of points.
  21495. * This can be an array of Points that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...],
  21496. * or the arguments passed can be all the points of the polygon e.g. `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the
  21497. * arguments passed can be flat x,y values e.g. `new PIXI.Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
  21498. *
  21499. * @class Phaser.Polygon
  21500. * @classdesc The polygon represents a list of orderded points in space
  21501. * @constructor
  21502. * @param {Array<Phaser.Point>|Array<number>} points - The array of Points.
  21503. */
  21504. Phaser.Polygon = function (points) {
  21505. PIXI.Polygon.call(this, points);
  21506. /**
  21507. * @property {number} type - The base object type.
  21508. */
  21509. this.type = Phaser.POLYGON;
  21510. };
  21511. Phaser.Polygon.prototype = Object.create(PIXI.Polygon.prototype);
  21512. Phaser.Polygon.prototype.constructor = Phaser.Polygon;
  21513. /**
  21514. * @author Richard Davey <rich@photonstorm.com>
  21515. * @copyright 2013 Photon Storm Ltd.
  21516. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21517. */
  21518. /**
  21519. * Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation.
  21520. *
  21521. * @class Phaser.Net
  21522. * @constructor
  21523. * @param {Phaser.Game} game - A reference to the currently running game.
  21524. */
  21525. Phaser.Net = function (game) {
  21526. this.game = game;
  21527. };
  21528. Phaser.Net.prototype = {
  21529. /**
  21530. * Returns the hostname given by the browser.
  21531. *
  21532. * @method Phaser.Net#getHostName
  21533. * @return {string}
  21534. */
  21535. getHostName: function () {
  21536. if (window.location && window.location.hostname) {
  21537. return window.location.hostname;
  21538. }
  21539. return null;
  21540. },
  21541. /**
  21542. * Compares the given domain name against the hostname of the browser containing the game.
  21543. * If the domain name is found it returns true.
  21544. * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc.
  21545. * Do not include 'http://' at the start.
  21546. *
  21547. * @method Phaser.Net#checkDomainName
  21548. * @param {string} domain
  21549. * @return {boolean} true if the given domain fragment can be found in the window.location.hostname
  21550. */
  21551. checkDomainName: function (domain) {
  21552. return window.location.hostname.indexOf(domain) !== -1;
  21553. },
  21554. /**
  21555. * Updates a value on the Query String and returns it in full.
  21556. * If the value doesn't already exist it is set.
  21557. * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string.
  21558. * Optionally you can redirect to the new url, or just return it as a string.
  21559. *
  21560. * @method Phaser.Net#updateQueryString
  21561. * @param {string} key - The querystring key to update.
  21562. * @param {string} value - The new value to be set. If it already exists it will be replaced.
  21563. * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring.
  21564. * @param {string} url - The URL to modify. If none is given it uses window.location.href.
  21565. * @return {string} If redirect is false then the modified url and query string is returned.
  21566. */
  21567. updateQueryString: function (key, value, redirect, url) {
  21568. if (typeof redirect === "undefined") { redirect = false; }
  21569. if (typeof url === "undefined" || url === '') { url = window.location.href; }
  21570. var output = '';
  21571. var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi");
  21572. if (re.test(url))
  21573. {
  21574. if (typeof value !== 'undefined' && value !== null)
  21575. {
  21576. output = url.replace(re, '$1' + key + "=" + value + '$2$3');
  21577. }
  21578. else
  21579. {
  21580. output = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
  21581. }
  21582. }
  21583. else
  21584. {
  21585. if (typeof value !== 'undefined' && value !== null)
  21586. {
  21587. var separator = url.indexOf('?') !== -1 ? '&' : '?';
  21588. var hash = url.split('#');
  21589. url = hash[0] + separator + key + '=' + value;
  21590. if (hash[1]) {
  21591. url += '#' + hash[1];
  21592. }
  21593. output = url;
  21594. }
  21595. else
  21596. {
  21597. output = url;
  21598. }
  21599. }
  21600. if (redirect)
  21601. {
  21602. window.location.href = output;
  21603. }
  21604. else
  21605. {
  21606. return output;
  21607. }
  21608. },
  21609. /**
  21610. * Returns the Query String as an object.
  21611. * If you specify a parameter it will return just the value of that parameter, should it exist.
  21612. *
  21613. * @method Phaser.Net#getQueryString
  21614. * @param {string} [parameter=''] - If specified this will return just the value for that key.
  21615. * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given.
  21616. */
  21617. getQueryString: function (parameter) {
  21618. if (typeof parameter === "undefined") { parameter = ''; }
  21619. var output = {};
  21620. var keyValues = location.search.substring(1).split('&');
  21621. for (var i in keyValues) {
  21622. var key = keyValues[i].split('=');
  21623. if (key.length > 1)
  21624. {
  21625. if (parameter && parameter == this.decodeURI(key[0]))
  21626. {
  21627. return this.decodeURI(key[1]);
  21628. }
  21629. else
  21630. {
  21631. output[this.decodeURI(key[0])] = this.decodeURI(key[1]);
  21632. }
  21633. }
  21634. }
  21635. return output;
  21636. },
  21637. /**
  21638. * Returns the Query String as an object.
  21639. * If you specify a parameter it will return just the value of that parameter, should it exist.
  21640. *
  21641. * @method Phaser.Net#decodeURI
  21642. * @param {string} value - The URI component to be decoded.
  21643. * @return {string} The decoded value.
  21644. */
  21645. decodeURI: function (value) {
  21646. return decodeURIComponent(value.replace(/\+/g, " "));
  21647. }
  21648. };
  21649. /**
  21650. * @author Richard Davey <rich@photonstorm.com>
  21651. * @copyright 2013 Photon Storm Ltd.
  21652. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21653. */
  21654. /**
  21655. * Phaser - TweenManager
  21656. *
  21657. * @class Phaser.TweenManager
  21658. * @classdesc
  21659. * Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated.
  21660. * Tweens are hooked into the game clock and pause system, adjusting based on the game state.
  21661. *
  21662. * TweenManager is based heavily on tween.js by http://soledadpenades.com.
  21663. * The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object.
  21664. * It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors.
  21665. * Please see https://github.com/sole/tween.js for a full list of contributors.
  21666. * @constructor
  21667. *
  21668. * @param {Phaser.Game} game - A reference to the currently running game.
  21669. */
  21670. Phaser.TweenManager = function (game) {
  21671. /**
  21672. * @property {Phaser.Game} game - Local reference to game.
  21673. */
  21674. this.game = game;
  21675. /**
  21676. * @property {array} _tweens - Description.
  21677. * @private
  21678. */
  21679. this._tweens = [];
  21680. /**
  21681. * @property {array} _add - Description.
  21682. * @private
  21683. */
  21684. this._add = [];
  21685. this.game.onPause.add(this.pauseAll, this);
  21686. this.game.onResume.add(this.resumeAll, this);
  21687. };
  21688. Phaser.TweenManager.prototype = {
  21689. /**
  21690. * Version number of this library.
  21691. * @property {string} REVISION
  21692. * @default
  21693. */
  21694. REVISION: '11dev',
  21695. /**
  21696. * Get all the tween objects in an array.
  21697. * @method Phaser.TweenManager#getAll
  21698. * @returns {Phaser.Tween[]} Array with all tween objects.
  21699. */
  21700. getAll: function () {
  21701. return this._tweens;
  21702. },
  21703. /**
  21704. * Remove all tween objects.
  21705. * @method Phaser.TweenManager#removeAll
  21706. */
  21707. removeAll: function () {
  21708. this._tweens = [];
  21709. },
  21710. /**
  21711. * Add a new tween into the TweenManager.
  21712. *
  21713. * @method Phaser.TweenManager#add
  21714. * @param {Phaser.Tween} tween - The tween object you want to add.
  21715. * @returns {Phaser.Tween} The tween object you added to the manager.
  21716. */
  21717. add: function ( tween ) {
  21718. this._add.push( tween );
  21719. },
  21720. /**
  21721. * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
  21722. *
  21723. * @method Phaser.TweenManager#create
  21724. * @param {Object} object - Object the tween will be run on.
  21725. * @returns {Phaser.Tween} The newly created tween object.
  21726. */
  21727. create: function (object) {
  21728. return new Phaser.Tween(object, this.game);
  21729. },
  21730. /**
  21731. * Remove a tween from this manager.
  21732. *
  21733. * @method Phaser.TweenManager#remove
  21734. * @param {Phaser.Tween} tween - The tween object you want to remove.
  21735. */
  21736. remove: function ( tween ) {
  21737. var i = this._tweens.indexOf( tween );
  21738. if ( i !== -1 ) {
  21739. this._tweens[i].pendingDelete = true;
  21740. }
  21741. },
  21742. /**
  21743. * Update all the tween objects you added to this manager.
  21744. *
  21745. * @method Phaser.TweenManager#update
  21746. * @returns {boolean} Return false if there's no tween to update, otherwise return true.
  21747. */
  21748. update: function () {
  21749. if ( this._tweens.length === 0 && this._add.length === 0 )
  21750. {
  21751. return false;
  21752. }
  21753. var i = 0;
  21754. var numTweens = this._tweens.length;
  21755. while ( i < numTweens ) {
  21756. if ( this._tweens[ i ].update( this.game.time.now ) ) {
  21757. i++;
  21758. } else {
  21759. this._tweens.splice( i, 1 );
  21760. numTweens--;
  21761. }
  21762. }
  21763. // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running
  21764. if (this._add.length > 0)
  21765. {
  21766. this._tweens = this._tweens.concat(this._add);
  21767. this._add.length = 0;
  21768. }
  21769. return true;
  21770. },
  21771. /**
  21772. * Checks to see if a particular Sprite is currently being tweened.
  21773. *
  21774. * @method Phaser.TweenManager#isTweening
  21775. * @param {object} object - The object to check for tweens against.
  21776. * @returns {boolean} Returns true if the object is currently being tweened, false if not.
  21777. */
  21778. isTweening: function(object) {
  21779. return this._tweens.some(function(tween) {
  21780. return tween._object === object;
  21781. });
  21782. },
  21783. /**
  21784. * Pauses all currently running tweens.
  21785. *
  21786. * @method Phaser.TweenManager#update
  21787. */
  21788. pauseAll: function () {
  21789. for (var i = this._tweens.length - 1; i >= 0; i--) {
  21790. this._tweens[i].pause();
  21791. }
  21792. },
  21793. /**
  21794. * Pauses all currently paused tweens.
  21795. *
  21796. * @method Phaser.TweenManager#resumeAll
  21797. */
  21798. resumeAll: function () {
  21799. for (var i = this._tweens.length - 1; i >= 0; i--) {
  21800. this._tweens[i].resume();
  21801. }
  21802. }
  21803. };
  21804. /**
  21805. * @author Richard Davey <rich@photonstorm.com>
  21806. * @copyright 2013 Photon Storm Ltd.
  21807. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21808. */
  21809. /**
  21810. * Tween constructor
  21811. * Create a new <code>Tween</code>.
  21812. *
  21813. * @class Phaser.Tween
  21814. * @constructor
  21815. * @param {object} object - Target object will be affected by this tween.
  21816. * @param {Phaser.Game} game - Current game instance.
  21817. */
  21818. Phaser.Tween = function (object, game) {
  21819. /**
  21820. * Reference to the target object.
  21821. * @property {object} _object
  21822. * @private
  21823. */
  21824. this._object = object;
  21825. /**
  21826. * @property {Phaser.Game} game - A reference to the currently running Game.
  21827. */
  21828. this.game = game;
  21829. /**
  21830. * @property {object} _manager - Description.
  21831. * @private
  21832. */
  21833. this._manager = this.game.tweens;
  21834. /**
  21835. * @property {object} _valuesStart - Description.
  21836. * @private
  21837. */
  21838. this._valuesStart = {};
  21839. /**
  21840. * @property {object} _valuesEnd - Description.
  21841. * @private
  21842. */
  21843. this._valuesEnd = {};
  21844. /**
  21845. * @property {object} _valuesStartRepeat - Description.
  21846. * @private
  21847. */
  21848. this._valuesStartRepeat = {};
  21849. /**
  21850. * @property {number} _duration - Description.
  21851. * @private
  21852. * @default
  21853. */
  21854. this._duration = 1000;
  21855. /**
  21856. * @property {number} _repeat - Description.
  21857. * @private
  21858. * @default
  21859. */
  21860. this._repeat = 0;
  21861. /**
  21862. * @property {boolean} _yoyo - Description.
  21863. * @private
  21864. * @default
  21865. */
  21866. this._yoyo = false;
  21867. /**
  21868. * @property {boolean} _reversed - Description.
  21869. * @private
  21870. * @default
  21871. */
  21872. this._reversed = false;
  21873. /**
  21874. * @property {number} _delayTime - Description.
  21875. * @private
  21876. * @default
  21877. */
  21878. this._delayTime = 0;
  21879. /**
  21880. * @property {Description} _startTime - Description.
  21881. * @private
  21882. * @default null
  21883. */
  21884. this._startTime = null;
  21885. /**
  21886. * @property {Description} _easingFunction - Description.
  21887. * @private
  21888. */
  21889. this._easingFunction = Phaser.Easing.Linear.None;
  21890. /**
  21891. * @property {Description} _interpolationFunction - Description.
  21892. * @private
  21893. */
  21894. this._interpolationFunction = Phaser.Math.linearInterpolation;
  21895. /**
  21896. * @property {Description} _chainedTweens - Description.
  21897. * @private
  21898. */
  21899. this._chainedTweens = [];
  21900. /**
  21901. * @property {Description} _onStartCallback - Description.
  21902. * @private
  21903. * @default
  21904. */
  21905. this._onStartCallback = null;
  21906. /**
  21907. * @property {boolean} _onStartCallbackFired - Description.
  21908. * @private
  21909. * @default
  21910. */
  21911. this._onStartCallbackFired = false;
  21912. /**
  21913. * @property {Description} _onUpdateCallback - Description.
  21914. * @private
  21915. * @default null
  21916. */
  21917. this._onUpdateCallback = null;
  21918. /**
  21919. * @property {Description} _onCompleteCallback - Description.
  21920. * @private
  21921. * @default null
  21922. */
  21923. this._onCompleteCallback = null;
  21924. /**
  21925. * @property {number} _pausedTime - Description.
  21926. * @private
  21927. * @default
  21928. */
  21929. this._pausedTime = 0;
  21930. /**
  21931. * @property {boolean} pendingDelete - If this tween is ready to be deleted by the TweenManager.
  21932. * @default
  21933. */
  21934. this.pendingDelete = false;
  21935. // Set all starting values present on the target object
  21936. for ( var field in object ) {
  21937. this._valuesStart[ field ] = parseFloat(object[field], 10);
  21938. }
  21939. /**
  21940. * @property {Phaser.Signal} onStart - Description.
  21941. */
  21942. this.onStart = new Phaser.Signal();
  21943. /**
  21944. * @property {Phaser.Signal} onComplete - Description.
  21945. */
  21946. this.onComplete = new Phaser.Signal();
  21947. /**
  21948. * @property {boolean} isRunning - Description.
  21949. * @default
  21950. */
  21951. this.isRunning = false;
  21952. };
  21953. Phaser.Tween.prototype = {
  21954. /**
  21955. * Configure the Tween
  21956. *
  21957. * @method Phaser.Tween#to
  21958. * @param {object} properties - Properties you want to tween.
  21959. * @param {number} duration - Duration of this tween.
  21960. * @param {function} ease - Easing function.
  21961. * @param {boolean} autoStart - Whether this tween will start automatically or not.
  21962. * @param {number} delay - Delay before this tween will start, defaults to 0 (no delay).
  21963. * @param {boolean} repeat - Should the tween automatically restart once complete? (ignores any chained tweens).
  21964. * @param {Phaser.Tween} yoyo - Description.
  21965. * @return {Phaser.Tween} Itself.
  21966. */
  21967. to: function ( properties, duration, ease, autoStart, delay, repeat, yoyo ) {
  21968. duration = duration || 1000;
  21969. ease = ease || null;
  21970. autoStart = autoStart || false;
  21971. delay = delay || 0;
  21972. repeat = repeat || 0;
  21973. yoyo = yoyo || false;
  21974. var self;
  21975. if (this._parent)
  21976. {
  21977. self = this._manager.create(this._object);
  21978. this._lastChild.chain(self);
  21979. this._lastChild = self;
  21980. }
  21981. else
  21982. {
  21983. self = this;
  21984. this._parent = this;
  21985. this._lastChild = this;
  21986. }
  21987. self._repeat = repeat;
  21988. self._duration = duration;
  21989. self._valuesEnd = properties;
  21990. if (ease !== null)
  21991. {
  21992. self._easingFunction = ease;
  21993. }
  21994. if (delay > 0)
  21995. {
  21996. self._delayTime = delay;
  21997. }
  21998. self._yoyo = yoyo;
  21999. if (autoStart) {
  22000. return this.start();
  22001. } else {
  22002. return this;
  22003. }
  22004. },
  22005. /**
  22006. * Starts the tween running. Can also be called by the autoStart parameter of Tween.to.
  22007. *
  22008. * @method Phaser.Tween#start
  22009. * @return {Phaser.Tween} Itself.
  22010. */
  22011. start: function () {
  22012. if (this.game === null || this._object === null) {
  22013. return;
  22014. }
  22015. this._manager.add(this);
  22016. this.onStart.dispatch(this._object);
  22017. this.isRunning = true;
  22018. this._onStartCallbackFired = false;
  22019. this._startTime = this.game.time.now + this._delayTime;
  22020. for ( var property in this._valuesEnd ) {
  22021. // check if an Array was provided as property value
  22022. if ( this._valuesEnd[ property ] instanceof Array ) {
  22023. if ( this._valuesEnd[ property ].length === 0 ) {
  22024. continue;
  22025. }
  22026. // create a local copy of the Array with the start value at the front
  22027. this._valuesEnd[ property ] = [ this._object[ property ] ].concat( this._valuesEnd[ property ] );
  22028. }
  22029. this._valuesStart[ property ] = this._object[ property ];
  22030. if ( ( this._valuesStart[ property ] instanceof Array ) === false ) {
  22031. this._valuesStart[ property ] *= 1.0; // Ensures we're using numbers, not strings
  22032. }
  22033. this._valuesStartRepeat[ property ] = this._valuesStart[ property ] || 0;
  22034. }
  22035. return this;
  22036. },
  22037. /**
  22038. * Stops the tween if running and removes it from the TweenManager. If there are any onComplete callbacks or events they are not dispatched.
  22039. *
  22040. * @method Phaser.Tween#stop
  22041. * @return {Phaser.Tween} Itself.
  22042. */
  22043. stop: function () {
  22044. this.isRunning = false;
  22045. this._manager.remove(this);
  22046. return this;
  22047. },
  22048. /**
  22049. * Sets a delay time before this tween will start.
  22050. *
  22051. * @method Phaser.Tween#delay
  22052. * @param {number} amount - The amount of the delay in ms.
  22053. * @return {Phaser.Tween} Itself.
  22054. */
  22055. delay: function ( amount ) {
  22056. this._delayTime = amount;
  22057. return this;
  22058. },
  22059. /**
  22060. * Sets the number of times this tween will repeat.
  22061. *
  22062. * @method Phaser.Tween#repeat
  22063. * @param {number} times - How many times to repeat.
  22064. * @return {Phaser.Tween} Itself.
  22065. */
  22066. repeat: function ( times ) {
  22067. this._repeat = times;
  22068. return this;
  22069. },
  22070. /**
  22071. * A tween that has yoyo set to true will run through from start to finish, then reverse from finish to start.
  22072. * Used in combination with repeat you can create endless loops.
  22073. *
  22074. * @method Phaser.Tween#yoyo
  22075. * @param {boolean} yoyo - Set to true to yoyo this tween.
  22076. * @return {Phaser.Tween} Itself.
  22077. */
  22078. yoyo: function( yoyo ) {
  22079. this._yoyo = yoyo;
  22080. return this;
  22081. },
  22082. /**
  22083. * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None.
  22084. *
  22085. * @method Phaser.Tween#easing
  22086. * @param {function} easing - The easing function this tween will use, i.e. Phaser.Easing.Linear.None.
  22087. * @return {Phaser.Tween} Itself.
  22088. */
  22089. easing: function ( easing ) {
  22090. this._easingFunction = easing;
  22091. return this;
  22092. },
  22093. /**
  22094. * Set interpolation function the tween will use, by default it uses Phaser.Math.linearInterpolation.
  22095. *
  22096. * @method Phaser.Tween#interpolation
  22097. * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default)
  22098. * @return {Phaser.Tween} Itself.
  22099. */
  22100. interpolation: function ( interpolation ) {
  22101. this._interpolationFunction = interpolation;
  22102. return this;
  22103. },
  22104. /**
  22105. * You can chain tweens together by passing a reference to the chain function. This enables one tween to call another on completion.
  22106. * You can pass as many tweens as you like to this function, they will each be chained in sequence.
  22107. *
  22108. * @method Phaser.Tween#chain
  22109. * @return {Phaser.Tween} Itself.
  22110. */
  22111. chain: function () {
  22112. this._chainedTweens = arguments;
  22113. return this;
  22114. },
  22115. /**
  22116. * Loop a chain of tweens
  22117. *
  22118. * Usage:
  22119. * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true)
  22120. * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None)
  22121. * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None)
  22122. * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None)
  22123. * .loop();
  22124. * @method Phaser.Tween#loop
  22125. * @return {Phaser.Tween} Itself.
  22126. */
  22127. loop: function() {
  22128. this._lastChild.chain(this);
  22129. return this;
  22130. },
  22131. /**
  22132. * Sets a callback to be fired when the tween starts. Note: callback will be called in the context of the global scope.
  22133. *
  22134. * @method Phaser.Tween#onStartCallback
  22135. * @param {function} callback - The callback to invoke on start.
  22136. * @return {Phaser.Tween} Itself.
  22137. */
  22138. onStartCallback: function ( callback ) {
  22139. this._onStartCallback = callback;
  22140. return this;
  22141. },
  22142. /**
  22143. * Sets a callback to be fired each time this tween updates. Note: callback will be called in the context of the global scope.
  22144. *
  22145. * @method Phaser.Tween#onUpdateCallback
  22146. * @param {function} callback - The callback to invoke each time this tween is updated.
  22147. * @return {Phaser.Tween} Itself.
  22148. */
  22149. onUpdateCallback: function ( callback ) {
  22150. this._onUpdateCallback = callback;
  22151. return this;
  22152. },
  22153. /**
  22154. * Sets a callback to be fired when the tween completes. Note: callback will be called in the context of the global scope.
  22155. *
  22156. * @method Phaser.Tween#onCompleteCallback
  22157. * @param {function} callback - The callback to invoke on completion.
  22158. * @return {Phaser.Tween} Itself.
  22159. */
  22160. onCompleteCallback: function ( callback ) {
  22161. this._onCompleteCallback = callback;
  22162. return this;
  22163. },
  22164. /**
  22165. * Pauses the tween.
  22166. *
  22167. * @method Phaser.Tween#pause
  22168. */
  22169. pause: function () {
  22170. this._paused = true;
  22171. this._pausedTime = this.game.time.now;
  22172. },
  22173. /**
  22174. * Resumes a paused tween.
  22175. *
  22176. * @method Phaser.Tween#resume
  22177. */
  22178. resume: function () {
  22179. this._paused = false;
  22180. this._startTime += (this.game.time.now - this._pausedTime);
  22181. },
  22182. /**
  22183. * Core tween update function called by the TweenManager. Does not need to be invoked directly.
  22184. *
  22185. * @method Phaser.Tween#update
  22186. * @param {number} time - A timestamp passed in by the TweenManager.
  22187. * @return {boolean} false if the tween has completed and should be deleted from the manager, otherwise true (still active).
  22188. */
  22189. update: function ( time ) {
  22190. if (this.pendingDelete)
  22191. {
  22192. return false;
  22193. }
  22194. if (this._paused || time < this._startTime) {
  22195. return true;
  22196. }
  22197. var property;
  22198. if ( time < this._startTime ) {
  22199. return true;
  22200. }
  22201. if ( this._onStartCallbackFired === false ) {
  22202. if ( this._onStartCallback !== null ) {
  22203. this._onStartCallback.call( this._object );
  22204. }
  22205. this._onStartCallbackFired = true;
  22206. }
  22207. var elapsed = ( time - this._startTime ) / this._duration;
  22208. elapsed = elapsed > 1 ? 1 : elapsed;
  22209. var value = this._easingFunction( elapsed );
  22210. for ( property in this._valuesEnd ) {
  22211. var start = this._valuesStart[ property ] || 0;
  22212. var end = this._valuesEnd[ property ];
  22213. if ( end instanceof Array ) {
  22214. this._object[ property ] = this._interpolationFunction( end, value );
  22215. } else {
  22216. // Parses relative end values with start as base (e.g.: +10, -3)
  22217. if ( typeof(end) === "string" ) {
  22218. end = start + parseFloat(end, 10);
  22219. }
  22220. // protect against non numeric properties.
  22221. if ( typeof(end) === "number" ) {
  22222. this._object[ property ] = start + ( end - start ) * value;
  22223. }
  22224. }
  22225. }
  22226. if ( this._onUpdateCallback !== null ) {
  22227. this._onUpdateCallback.call( this._object, value );
  22228. }
  22229. if ( elapsed == 1 ) {
  22230. if ( this._repeat > 0 ) {
  22231. if ( isFinite( this._repeat ) ) {
  22232. this._repeat--;
  22233. }
  22234. // reassign starting values, restart by making startTime = now
  22235. for ( property in this._valuesStartRepeat ) {
  22236. if ( typeof( this._valuesEnd[ property ] ) === "string" ) {
  22237. this._valuesStartRepeat[ property ] = this._valuesStartRepeat[ property ] + parseFloat(this._valuesEnd[ property ], 10);
  22238. }
  22239. if (this._yoyo) {
  22240. var tmp = this._valuesStartRepeat[ property ];
  22241. this._valuesStartRepeat[ property ] = this._valuesEnd[ property ];
  22242. this._valuesEnd[ property ] = tmp;
  22243. this._reversed = !this._reversed;
  22244. }
  22245. this._valuesStart[ property ] = this._valuesStartRepeat[ property ];
  22246. }
  22247. this._startTime = time + this._delayTime;
  22248. this.onComplete.dispatch(this._object);
  22249. if ( this._onCompleteCallback !== null ) {
  22250. this._onCompleteCallback.call( this._object );
  22251. }
  22252. return true;
  22253. } else {
  22254. this.isRunning = false;
  22255. this.onComplete.dispatch(this._object);
  22256. if ( this._onCompleteCallback !== null ) {
  22257. this._onCompleteCallback.call( this._object );
  22258. }
  22259. for ( var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i ++ ) {
  22260. this._chainedTweens[ i ].start( time );
  22261. }
  22262. return false;
  22263. }
  22264. }
  22265. return true;
  22266. }
  22267. };
  22268. /* jshint curly: false */
  22269. /**
  22270. * @author Richard Davey <rich@photonstorm.com>
  22271. * @copyright 2013 Photon Storm Ltd.
  22272. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  22273. */
  22274. /**
  22275. * A collection of easing methods defining ease-in ease-out curves.
  22276. *
  22277. * @class Phaser.Easing
  22278. */
  22279. Phaser.Easing = {
  22280. /**
  22281. * Linear easing.
  22282. *
  22283. * @class Phaser.Easing.Linear
  22284. */
  22285. Linear: {
  22286. /**
  22287. * Ease-in.
  22288. *
  22289. * @method Phaser.Easing.Linear#In
  22290. * @param {number} k - The value to be tweened.
  22291. * @returns {number} k^2.
  22292. */
  22293. None: function ( k ) {
  22294. return k;
  22295. }
  22296. },
  22297. /**
  22298. * Quadratic easing.
  22299. *
  22300. * @class Phaser.Easing.Quadratic
  22301. */
  22302. Quadratic: {
  22303. /**
  22304. * Ease-in.
  22305. *
  22306. * @method Phaser.Easing.Quadratic#In
  22307. * @param {number} k - The value to be tweened.
  22308. * @returns {number} k^2.
  22309. */
  22310. In: function ( k ) {
  22311. return k * k;
  22312. },
  22313. /**
  22314. * Ease-out.
  22315. *
  22316. * @method Phaser.Easing.Quadratic#Out
  22317. * @param {number} k - The value to be tweened.
  22318. * @returns {number} k* (2-k).
  22319. */
  22320. Out: function ( k ) {
  22321. return k * ( 2 - k );
  22322. },
  22323. /**
  22324. * Ease-in/out.
  22325. *
  22326. * @method Phaser.Easing.Quadratic#InOut
  22327. * @param {number} k - The value to be tweened.
  22328. * @returns {number} The tweened value.
  22329. */
  22330. InOut: function ( k ) {
  22331. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  22332. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  22333. }
  22334. },
  22335. /**
  22336. * Cubic easing.
  22337. *
  22338. * @class Phaser.Easing.Cubic
  22339. */
  22340. Cubic: {
  22341. /**
  22342. * Cubic ease-in.
  22343. *
  22344. * @method Phaser.Easing.Cubic#In
  22345. * @param {number} k - The value to be tweened.
  22346. * @returns {number} The tweened value.
  22347. */
  22348. In: function ( k ) {
  22349. return k * k * k;
  22350. },
  22351. /**
  22352. * Cubic ease-out.
  22353. *
  22354. * @method Phaser.Easing.Cubic#Out
  22355. * @param {number} k - The value to be tweened.
  22356. * @returns {number} The tweened value.
  22357. */
  22358. Out: function ( k ) {
  22359. return --k * k * k + 1;
  22360. },
  22361. /**
  22362. * Cubic ease-in/out.
  22363. *
  22364. * @method Phaser.Easing.Cubic#InOut
  22365. * @param {number} k - The value to be tweened.
  22366. * @returns {number} The tweened value.
  22367. */
  22368. InOut: function ( k ) {
  22369. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k;
  22370. return 0.5 * ( ( k -= 2 ) * k * k + 2 );
  22371. }
  22372. },
  22373. /**
  22374. * Quartic easing.
  22375. *
  22376. * @class Phaser.Easing.Quartic
  22377. */
  22378. Quartic: {
  22379. /**
  22380. * Quartic ease-in.
  22381. *
  22382. * @method Phaser.Easing.Quartic#In
  22383. * @param {number} k - The value to be tweened.
  22384. * @returns {number} The tweened value.
  22385. */
  22386. In: function ( k ) {
  22387. return k * k * k * k;
  22388. },
  22389. /**
  22390. * Quartic ease-out.
  22391. *
  22392. * @method Phaser.Easing.Quartic#Out
  22393. * @param {number} k - The value to be tweened.
  22394. * @returns {number} The tweened value.
  22395. */
  22396. Out: function ( k ) {
  22397. return 1 - ( --k * k * k * k );
  22398. },
  22399. /**
  22400. * Quartic ease-in/out.
  22401. *
  22402. * @method Phaser.Easing.Quartic#InOut
  22403. * @param {number} k - The value to be tweened.
  22404. * @returns {number} The tweened value.
  22405. */
  22406. InOut: function ( k ) {
  22407. if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k;
  22408. return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 );
  22409. }
  22410. },
  22411. /**
  22412. * Quintic easing.
  22413. *
  22414. * @class Phaser.Easing.Quintic
  22415. */
  22416. Quintic: {
  22417. /**
  22418. * Quintic ease-in.
  22419. *
  22420. * @method Phaser.Easing.Quintic#In
  22421. * @param {number} k - The value to be tweened.
  22422. * @returns {number} The tweened value.
  22423. */
  22424. In: function ( k ) {
  22425. return k * k * k * k * k;
  22426. },
  22427. /**
  22428. * Quintic ease-out.
  22429. *
  22430. * @method Phaser.Easing.Quintic#Out
  22431. * @param {number} k - The value to be tweened.
  22432. * @returns {number} The tweened value.
  22433. */
  22434. Out: function ( k ) {
  22435. return --k * k * k * k * k + 1;
  22436. },
  22437. /**
  22438. * Quintic ease-in/out.
  22439. *
  22440. * @method Phaser.Easing.Quintic#InOut
  22441. * @param {number} k - The value to be tweened.
  22442. * @returns {number} The tweened value.
  22443. */
  22444. InOut: function ( k ) {
  22445. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k;
  22446. return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 );
  22447. }
  22448. },
  22449. /**
  22450. * Sinusoidal easing.
  22451. *
  22452. * @class Phaser.Easing.Sinusoidal
  22453. */
  22454. Sinusoidal: {
  22455. /**
  22456. * Sinusoidal ease-in.
  22457. *
  22458. * @method Phaser.Easing.Sinusoidal#In
  22459. * @param {number} k - The value to be tweened.
  22460. * @returns {number} The tweened value.
  22461. */
  22462. In: function ( k ) {
  22463. return 1 - Math.cos( k * Math.PI / 2 );
  22464. },
  22465. /**
  22466. * Sinusoidal ease-out.
  22467. *
  22468. * @method Phaser.Easing.Sinusoidal#Out
  22469. * @param {number} k - The value to be tweened.
  22470. * @returns {number} The tweened value.
  22471. */
  22472. Out: function ( k ) {
  22473. return Math.sin( k * Math.PI / 2 );
  22474. },
  22475. /**
  22476. * Sinusoidal ease-in/out.
  22477. *
  22478. * @method Phaser.Easing.Sinusoidal#InOut
  22479. * @param {number} k - The value to be tweened.
  22480. * @returns {number} The tweened value.
  22481. */
  22482. InOut: function ( k ) {
  22483. return 0.5 * ( 1 - Math.cos( Math.PI * k ) );
  22484. }
  22485. },
  22486. /**
  22487. * Exponential easing.
  22488. *
  22489. * @class Phaser.Easing.Exponential
  22490. */
  22491. Exponential: {
  22492. /**
  22493. * Exponential ease-in.
  22494. *
  22495. * @method Phaser.Easing.Exponential#In
  22496. * @param {number} k - The value to be tweened.
  22497. * @returns {number} The tweened value.
  22498. */
  22499. In: function ( k ) {
  22500. return k === 0 ? 0 : Math.pow( 1024, k - 1 );
  22501. },
  22502. /**
  22503. * Exponential ease-out.
  22504. *
  22505. * @method Phaser.Easing.Exponential#Out
  22506. * @param {number} k - The value to be tweened.
  22507. * @returns {number} The tweened value.
  22508. */
  22509. Out: function ( k ) {
  22510. return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k );
  22511. },
  22512. /**
  22513. * Exponential ease-in/out.
  22514. *
  22515. * @method Phaser.Easing.Exponential#InOut
  22516. * @param {number} k - The value to be tweened.
  22517. * @returns {number} The tweened value.
  22518. */
  22519. InOut: function ( k ) {
  22520. if ( k === 0 ) return 0;
  22521. if ( k === 1 ) return 1;
  22522. if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 );
  22523. return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 );
  22524. }
  22525. },
  22526. /**
  22527. * Circular easing.
  22528. *
  22529. * @class Phaser.Easing.Circular
  22530. */
  22531. Circular: {
  22532. /**
  22533. * Circular ease-in.
  22534. *
  22535. * @method Phaser.Easing.Circular#In
  22536. * @param {number} k - The value to be tweened.
  22537. * @returns {number} The tweened value.
  22538. */
  22539. In: function ( k ) {
  22540. return 1 - Math.sqrt( 1 - k * k );
  22541. },
  22542. /**
  22543. * Circular ease-out.
  22544. *
  22545. * @method Phaser.Easing.Circular#Out
  22546. * @param {number} k - The value to be tweened.
  22547. * @returns {number} The tweened value.
  22548. */
  22549. Out: function ( k ) {
  22550. return Math.sqrt( 1 - ( --k * k ) );
  22551. },
  22552. /**
  22553. * Circular ease-in/out.
  22554. *
  22555. * @method Phaser.Easing.Circular#InOut
  22556. * @param {number} k - The value to be tweened.
  22557. * @returns {number} The tweened value.
  22558. */
  22559. InOut: function ( k ) {
  22560. if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1);
  22561. return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1);
  22562. }
  22563. },
  22564. /**
  22565. * Elastic easing.
  22566. *
  22567. * @class Phaser.Easing.Elastic
  22568. */
  22569. Elastic: {
  22570. /**
  22571. * Elastic ease-in.
  22572. *
  22573. * @method Phaser.Easing.Elastic#In
  22574. * @param {number} k - The value to be tweened.
  22575. * @returns {number} The tweened value.
  22576. */
  22577. In: function ( k ) {
  22578. var s, a = 0.1, p = 0.4;
  22579. if ( k === 0 ) return 0;
  22580. if ( k === 1 ) return 1;
  22581. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  22582. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  22583. return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  22584. },
  22585. /**
  22586. * Elastic ease-out.
  22587. *
  22588. * @method Phaser.Easing.Elastic#Out
  22589. * @param {number} k - The value to be tweened.
  22590. * @returns {number} The tweened value.
  22591. */
  22592. Out: function ( k ) {
  22593. var s, a = 0.1, p = 0.4;
  22594. if ( k === 0 ) return 0;
  22595. if ( k === 1 ) return 1;
  22596. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  22597. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  22598. return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );
  22599. },
  22600. /**
  22601. * Elastic ease-in/out.
  22602. *
  22603. * @method Phaser.Easing.Elastic#InOut
  22604. * @param {number} k - The value to be tweened.
  22605. * @returns {number} The tweened value.
  22606. */
  22607. InOut: function ( k ) {
  22608. var s, a = 0.1, p = 0.4;
  22609. if ( k === 0 ) return 0;
  22610. if ( k === 1 ) return 1;
  22611. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  22612. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  22613. if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  22614. return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1;
  22615. }
  22616. },
  22617. /**
  22618. * Back easing.
  22619. *
  22620. * @class Phaser.Easing.Back
  22621. */
  22622. Back: {
  22623. /**
  22624. * Back ease-in.
  22625. *
  22626. * @method Phaser.Easing.Back#In
  22627. * @param {number} k - The value to be tweened.
  22628. * @returns {number} The tweened value.
  22629. */
  22630. In: function ( k ) {
  22631. var s = 1.70158;
  22632. return k * k * ( ( s + 1 ) * k - s );
  22633. },
  22634. /**
  22635. * Back ease-out.
  22636. *
  22637. * @method Phaser.Easing.Back#Out
  22638. * @param {number} k - The value to be tweened.
  22639. * @returns {number} The tweened value.
  22640. */
  22641. Out: function ( k ) {
  22642. var s = 1.70158;
  22643. return --k * k * ( ( s + 1 ) * k + s ) + 1;
  22644. },
  22645. /**
  22646. * Back ease-in/out.
  22647. *
  22648. * @method Phaser.Easing.Back#InOut
  22649. * @param {number} k - The value to be tweened.
  22650. * @returns {number} The tweened value.
  22651. */
  22652. InOut: function ( k ) {
  22653. var s = 1.70158 * 1.525;
  22654. if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) );
  22655. return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 );
  22656. }
  22657. },
  22658. /**
  22659. * Bounce easing.
  22660. *
  22661. * @class Phaser.Easing.Bounce
  22662. */
  22663. Bounce: {
  22664. /**
  22665. * Bounce ease-in.
  22666. *
  22667. * @method Phaser.Easing.Bounce#In
  22668. * @param {number} k - The value to be tweened.
  22669. * @returns {number} The tweened value.
  22670. */
  22671. In: function ( k ) {
  22672. return 1 - Phaser.Easing.Bounce.Out( 1 - k );
  22673. },
  22674. /**
  22675. * Bounce ease-out.
  22676. *
  22677. * @method Phaser.Easing.Bounce#Out
  22678. * @param {number} k - The value to be tweened.
  22679. * @returns {number} The tweened value.
  22680. */
  22681. Out: function ( k ) {
  22682. if ( k < ( 1 / 2.75 ) ) {
  22683. return 7.5625 * k * k;
  22684. } else if ( k < ( 2 / 2.75 ) ) {
  22685. return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
  22686. } else if ( k < ( 2.5 / 2.75 ) ) {
  22687. return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
  22688. } else {
  22689. return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
  22690. }
  22691. },
  22692. /**
  22693. * Bounce ease-in/out.
  22694. *
  22695. * @method Phaser.Easing.Bounce#InOut
  22696. * @param {number} k - The value to be tweened.
  22697. * @returns {number} The tweened value.
  22698. */
  22699. InOut: function ( k ) {
  22700. if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5;
  22701. return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5;
  22702. }
  22703. }
  22704. };
  22705. /**
  22706. * @author Richard Davey <rich@photonstorm.com>
  22707. * @copyright 2013 Photon Storm Ltd.
  22708. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  22709. */
  22710. /**
  22711. * Time constructor.
  22712. *
  22713. * @class Phaser.Time
  22714. * @classdesc This is the core internal game clock. It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens.
  22715. * @constructor
  22716. * @param {Phaser.Game} game A reference to the currently running game.
  22717. */
  22718. Phaser.Time = function (game) {
  22719. /**
  22720. * @property {Phaser.Game} game - Local reference to game.
  22721. */
  22722. this.game = game;
  22723. /**
  22724. * @property {number} _started - The time at which the Game instance started.
  22725. * @private
  22726. */
  22727. this._started = 0;
  22728. /**
  22729. * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over.
  22730. * @private
  22731. */
  22732. this._timeLastSecond = 0;
  22733. /**
  22734. * @property {number} _pauseStarted - The time the game started being paused.
  22735. * @private
  22736. */
  22737. this._pauseStarted = 0;
  22738. /**
  22739. * @property {number} physicsElapsed - The elapsed time calculated for the physics motion updates.
  22740. */
  22741. this.physicsElapsed = 0;
  22742. /**
  22743. * @property {number} time - Game time counter.
  22744. */
  22745. this.time = 0;
  22746. /**
  22747. * @property {number} pausedTime - Records how long the game has been paused for. Is reset each time the game pauses.
  22748. */
  22749. this.pausedTime = 0;
  22750. /**
  22751. * @property {number} now - The time right now.
  22752. */
  22753. this.now = 0;
  22754. /**
  22755. * @property {number} elapsed - Elapsed time since the last frame.
  22756. */
  22757. this.elapsed = 0;
  22758. /**
  22759. * @property {number} fps - Frames per second.
  22760. */
  22761. this.fps = 0;
  22762. /**
  22763. * @property {number} fpsMin - The lowest rate the fps has dropped to.
  22764. */
  22765. this.fpsMin = 1000;
  22766. /**
  22767. * @property {number} fpsMax - The highest rate the fps has reached (usually no higher than 60fps).
  22768. */
  22769. this.fpsMax = 0;
  22770. /**
  22771. * @property {number} msMin - The minimum amount of time the game has taken between two frames.
  22772. * @default
  22773. */
  22774. this.msMin = 1000;
  22775. /**
  22776. * @property {number} msMax - The maximum amount of time the game has taken between two frames.
  22777. */
  22778. this.msMax = 0;
  22779. /**
  22780. * @property {number} frames - The number of frames record in the last second.
  22781. */
  22782. this.frames = 0;
  22783. /**
  22784. * @property {number} pauseDuration - Records how long the game was paused for in miliseconds.
  22785. */
  22786. this.pauseDuration = 0;
  22787. /**
  22788. * @property {number} timeToCall - The value that setTimeout needs to work out when to next update
  22789. */
  22790. this.timeToCall = 0;
  22791. /**
  22792. * @property {number} lastTime - Internal value used by timeToCall as part of the setTimeout loop
  22793. */
  22794. this.lastTime = 0;
  22795. // Listen for game pause/resume events
  22796. this.game.onPause.add(this.gamePaused, this);
  22797. this.game.onResume.add(this.gameResumed, this);
  22798. /**
  22799. * @property {boolean} _justResumed - Internal value used to recover from the game pause state.
  22800. * @private
  22801. */
  22802. this._justResumed = false;
  22803. };
  22804. Phaser.Time.prototype = {
  22805. /**
  22806. * Updates the game clock and calculate the fps. This is called automatically by Phaser.Game.
  22807. * @method Phaser.Time#update
  22808. * @param {number} time - The current timestamp, either performance.now or Date.now depending on the browser.
  22809. */
  22810. update: function (time) {
  22811. this.now = time;
  22812. if (this._justResumed)
  22813. {
  22814. this.time = this.now;
  22815. this._justResumed = false;
  22816. }
  22817. this.timeToCall = this.game.math.max(0, 16 - (time - this.lastTime));
  22818. this.elapsed = this.now - this.time;
  22819. this.msMin = this.game.math.min(this.msMin, this.elapsed);
  22820. this.msMax = this.game.math.max(this.msMax, this.elapsed);
  22821. this.frames++;
  22822. if (this.now > this._timeLastSecond + 1000)
  22823. {
  22824. this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond));
  22825. this.fpsMin = this.game.math.min(this.fpsMin, this.fps);
  22826. this.fpsMax = this.game.math.max(this.fpsMax, this.fps);
  22827. this._timeLastSecond = this.now;
  22828. this.frames = 0;
  22829. }
  22830. this.time = this.now;
  22831. this.lastTime = time + this.timeToCall;
  22832. this.physicsElapsed = 1.0 * (this.elapsed / 1000);
  22833. // Clamp the delta
  22834. if (this.physicsElapsed > 1)
  22835. {
  22836. this.physicsElapsed = 1;
  22837. }
  22838. // Paused?
  22839. if (this.game.paused)
  22840. {
  22841. this.pausedTime = this.now - this._pauseStarted;
  22842. }
  22843. },
  22844. /**
  22845. * Called when the game enters a paused state.
  22846. * @method Phaser.Time#gamePaused
  22847. * @private
  22848. */
  22849. gamePaused: function () {
  22850. this._pauseStarted = this.now;
  22851. },
  22852. /**
  22853. * Called when the game resumes from a paused state.
  22854. * @method Phaser.Time#gameResumed
  22855. * @private
  22856. */
  22857. gameResumed: function () {
  22858. // Level out the elapsed timer to avoid spikes
  22859. this.time = Date.now();
  22860. this.pauseDuration = this.pausedTime;
  22861. this._justResumed = true;
  22862. },
  22863. /**
  22864. * The number of seconds that have elapsed since the game was started.
  22865. * @method Phaser.Time#totalElapsedSeconds
  22866. * @return {number}
  22867. */
  22868. totalElapsedSeconds: function() {
  22869. return (this.now - this._started) * 0.001;
  22870. },
  22871. /**
  22872. * How long has passed since the given time.
  22873. * @method Phaser.Time#elapsedSince
  22874. * @param {number} since - The time you want to measure against.
  22875. * @return {number} The difference between the given time and now.
  22876. */
  22877. elapsedSince: function (since) {
  22878. return this.now - since;
  22879. },
  22880. /**
  22881. * How long has passed since the given time (in seconds).
  22882. * @method Phaser.Time#elapsedSecondsSince
  22883. * @param {number} since - The time you want to measure (in seconds).
  22884. * @return {number} Duration between given time and now (in seconds).
  22885. */
  22886. elapsedSecondsSince: function (since) {
  22887. return (this.now - since) * 0.001;
  22888. },
  22889. /**
  22890. * Resets the private _started value to now.
  22891. * @method Phaser.Time#reset
  22892. */
  22893. reset: function () {
  22894. this._started = this.now;
  22895. }
  22896. };
  22897. /**
  22898. * @author Richard Davey <rich@photonstorm.com>
  22899. * @copyright 2013 Photon Storm Ltd.
  22900. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  22901. */
  22902. /**
  22903. * Timer constructor.
  22904. *
  22905. * @class Phaser.Timer
  22906. * @classdesc A Timer
  22907. * @constructor
  22908. * @param {Phaser.Game} game A reference to the currently running game.
  22909. */
  22910. Phaser.Timer = function (game) {
  22911. /**
  22912. * @property {Phaser.Game} game - Local reference to game.
  22913. */
  22914. this.game = game;
  22915. /**
  22916. * The time at which this Timer instance started.
  22917. * @property {number} _started
  22918. * @private
  22919. * @default
  22920. */
  22921. this._started = 0;
  22922. /**
  22923. * The time (in ms) that the last second counter ticked over.
  22924. * @property {number} _timeLastSecond
  22925. * @private
  22926. * @default
  22927. */
  22928. this._timeLastSecond = 0;
  22929. this.running = false;
  22930. this.events = [];
  22931. this.onEvent = new Phaser.Signal();
  22932. // Need to add custom FPS rate, for now we'll just use seconds
  22933. }
  22934. Phaser.Timer.prototype = {
  22935. // delay could be from now, when the timer is created, or relative to an already running timer
  22936. // add: function (delay, callback, callbackContext) {
  22937. add: function (delay) {
  22938. this.events.push({
  22939. delay: delay,
  22940. dispatched: false,
  22941. args: Array.prototype.splice.call(arguments, 1)
  22942. });
  22943. // this.events.push({
  22944. // delay: delay,
  22945. // dispatched: false,
  22946. // callback: callback,
  22947. // callbackContext: callbackContext,
  22948. // args: Array.prototype.splice.call(arguments, 3)
  22949. // });
  22950. },
  22951. start: function() {
  22952. this._started = this.game.time.now;
  22953. this.running = true;
  22954. // sort the events based on delay here, also don't run unless events is populated
  22955. // add ability to auto-stop once all events are done
  22956. // add support for maximum duration
  22957. // add support for delay before starting
  22958. // add signals?
  22959. },
  22960. stop: function() {
  22961. this.running = false;
  22962. this.events.length = 0;
  22963. },
  22964. update: function() {
  22965. // TODO: Game Paused support
  22966. if (this.running)
  22967. {
  22968. var seconds = this.seconds();
  22969. for (var i = 0, len = this.events.length; i < len; i++)
  22970. {
  22971. if (this.events[i].dispatched === false && seconds >= this.events[i].delay)
  22972. {
  22973. this.events[i].dispatched = true;
  22974. // this.events[i].callback.apply(this.events[i].callbackContext, this.events[i].args);
  22975. this.onEvent.dispatch.apply(this, this.events[i].args);
  22976. // ought to slice it now
  22977. }
  22978. }
  22979. }
  22980. },
  22981. seconds: function() {
  22982. return (this.game.time.now - this._started) * 0.001;
  22983. }
  22984. }
  22985. /**
  22986. * @author Richard Davey <rich@photonstorm.com>
  22987. * @copyright 2013 Photon Storm Ltd.
  22988. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  22989. */
  22990. /**
  22991. * The Animation Manager is used to add, play and update Phaser Animations.
  22992. * Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance.
  22993. *
  22994. * @class Phaser.AnimationManager
  22995. * @constructor
  22996. * @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager.
  22997. */
  22998. Phaser.AnimationManager = function (sprite) {
  22999. /**
  23000. * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager.
  23001. */
  23002. this.sprite = sprite;
  23003. /**
  23004. * @property {Phaser.Game} game - A reference to the currently running Game.
  23005. */
  23006. this.game = sprite.game;
  23007. /**
  23008. * @property {Phaser.Frame} currentFrame - The currently displayed Frame of animation, if any.
  23009. * @default
  23010. */
  23011. this.currentFrame = null;
  23012. /**
  23013. * @property {boolean} updateIfVisible - Should the animation data continue to update even if the Sprite.visible is set to false.
  23014. * @default
  23015. */
  23016. this.updateIfVisible = true;
  23017. /**
  23018. * @property {boolean} isLoaded - Set to true once animation data has been loaded.
  23019. * @default
  23020. */
  23021. this.isLoaded = false;
  23022. /**
  23023. * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData.
  23024. * @private
  23025. * @default
  23026. */
  23027. this._frameData = null;
  23028. /**
  23029. * @property {object} _anims - An internal object that stores all of the Animation instances.
  23030. * @private
  23031. */
  23032. this._anims = {};
  23033. /**
  23034. * @property {object} _outputFrames - An internal object to help avoid gc.
  23035. * @private
  23036. */
  23037. this._outputFrames = [];
  23038. };
  23039. Phaser.AnimationManager.prototype = {
  23040. /**
  23041. * Loads FrameData into the internal temporary vars and resets the frame index to zero.
  23042. * This is called automatically when a new Sprite is created.
  23043. *
  23044. * @method Phaser.AnimationManager#loadFrameData
  23045. * @private
  23046. * @param {Phaser.FrameData} frameData - The FrameData set to load.
  23047. */
  23048. loadFrameData: function (frameData) {
  23049. this._frameData = frameData;
  23050. this.frame = 0;
  23051. this.isLoaded = true;
  23052. },
  23053. /**
  23054. * Adds a new animation under the given key. Optionally set the frames, frame rate and loop.
  23055. * Animations added in this way are played back with the play function.
  23056. *
  23057. * @method Phaser.AnimationManager#add
  23058. * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk".
  23059. * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used.
  23060. * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
  23061. * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
  23062. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings?
  23063. * @return {Phaser.Animation} The Animation object that was created.
  23064. */
  23065. add: function (name, frames, frameRate, loop, useNumericIndex) {
  23066. if (this._frameData == null)
  23067. {
  23068. console.warn('No FrameData available for Phaser.Animation ' + name);
  23069. return;
  23070. }
  23071. frameRate = frameRate || 60;
  23072. if (typeof loop === 'undefined') { loop = false; }
  23073. // If they didn't set the useNumericIndex then let's at least try and guess it
  23074. if (typeof useNumericIndex === 'undefined')
  23075. {
  23076. if (frames && typeof frames[0] === 'number')
  23077. {
  23078. useNumericIndex = true;
  23079. }
  23080. else
  23081. {
  23082. useNumericIndex = false;
  23083. }
  23084. }
  23085. // Create the signals the AnimationManager will emit
  23086. if (this.sprite.events.onAnimationStart == null)
  23087. {
  23088. this.sprite.events.onAnimationStart = new Phaser.Signal();
  23089. this.sprite.events.onAnimationComplete = new Phaser.Signal();
  23090. this.sprite.events.onAnimationLoop = new Phaser.Signal();
  23091. }
  23092. this._outputFrames.length = 0;
  23093. this._frameData.getFrameIndexes(frames, useNumericIndex, this._outputFrames);
  23094. this._anims[name] = new Phaser.Animation(this.game, this.sprite, name, this._frameData, this._outputFrames, frameRate, loop);
  23095. this.currentAnim = this._anims[name];
  23096. this.currentFrame = this.currentAnim.currentFrame;
  23097. this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  23098. return this._anims[name];
  23099. },
  23100. /**
  23101. * Check whether the frames in the given array are valid and exist.
  23102. *
  23103. * @method Phaser.AnimationManager#validateFrames
  23104. * @param {Array} frames - An array of frames to be validated.
  23105. * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false)
  23106. * @return {boolean} True if all given Frames are valid, otherwise false.
  23107. */
  23108. validateFrames: function (frames, useNumericIndex) {
  23109. if (typeof useNumericIndex == 'undefined') { useNumericIndex = true; }
  23110. for (var i = 0; i < frames.length; i++)
  23111. {
  23112. if (useNumericIndex === true)
  23113. {
  23114. if (frames[i] > this._frameData.total)
  23115. {
  23116. return false;
  23117. }
  23118. }
  23119. else
  23120. {
  23121. if (this._frameData.checkFrameName(frames[i]) === false)
  23122. {
  23123. return false;
  23124. }
  23125. }
  23126. }
  23127. return true;
  23128. },
  23129. /**
  23130. * Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
  23131. * If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
  23132. *
  23133. * @method Phaser.AnimationManager#play
  23134. * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
  23135. * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
  23136. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  23137. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  23138. * @return {Phaser.Animation} A reference to playing Animation instance.
  23139. */
  23140. play: function (name, frameRate, loop, killOnComplete) {
  23141. if (this._anims[name])
  23142. {
  23143. if (this.currentAnim == this._anims[name])
  23144. {
  23145. if (this.currentAnim.isPlaying === false)
  23146. {
  23147. this.currentAnim.paused = false;
  23148. return this.currentAnim.play(frameRate, loop, killOnComplete);
  23149. }
  23150. }
  23151. else
  23152. {
  23153. this.currentAnim = this._anims[name];
  23154. this.currentAnim.paused = false;
  23155. return this.currentAnim.play(frameRate, loop, killOnComplete);
  23156. }
  23157. }
  23158. },
  23159. /**
  23160. * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped.
  23161. * The currentAnim property of the AnimationManager is automatically set to the animation given.
  23162. *
  23163. * @method Phaser.AnimationManager#stop
  23164. * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped.
  23165. * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false)
  23166. */
  23167. stop: function (name, resetFrame) {
  23168. if (typeof resetFrame == 'undefined') { resetFrame = false; }
  23169. if (typeof name == 'string')
  23170. {
  23171. if (this._anims[name])
  23172. {
  23173. this.currentAnim = this._anims[name];
  23174. this.currentAnim.stop(resetFrame);
  23175. }
  23176. }
  23177. else
  23178. {
  23179. if (this.currentAnim)
  23180. {
  23181. this.currentAnim.stop(resetFrame);
  23182. }
  23183. }
  23184. },
  23185. /**
  23186. * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events.
  23187. *
  23188. * @method Phaser.AnimationManager#update
  23189. * @protected
  23190. * @return {boolean} True if a new animation frame has been set, otherwise false.
  23191. */
  23192. update: function () {
  23193. if (this.updateIfVisible && this.sprite.visible === false)
  23194. {
  23195. return false;
  23196. }
  23197. if (this.currentAnim && this.currentAnim.update() === true)
  23198. {
  23199. this.currentFrame = this.currentAnim.currentFrame;
  23200. this.sprite.currentFrame = this.currentFrame;
  23201. return true;
  23202. }
  23203. return false;
  23204. },
  23205. /**
  23206. * Returns an animation that was previously added by name.
  23207. *
  23208. * @method Phaser.AnimationManager#getAnimation
  23209. * @param {string} name - The name of the animation to be returned, e.g. "fire".
  23210. * @return {Phaser.Animation|boolean} The Animation instance, if found, otherwise false.
  23211. */
  23212. getAnimation: function (name) {
  23213. if (typeof name == 'string')
  23214. {
  23215. if (this._anims[name])
  23216. {
  23217. return this._anims[name];
  23218. }
  23219. }
  23220. return false;
  23221. },
  23222. /**
  23223. * Refreshes the current frame data back to the parent Sprite and also resets the texture data.
  23224. *
  23225. * @method Phaser.AnimationManager#refreshFrame
  23226. */
  23227. refreshFrame: function () {
  23228. this.sprite.currentFrame = this.currentFrame;
  23229. this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  23230. },
  23231. /**
  23232. * Destroys all references this AnimationManager contains. Sets the _anims to a new object and nulls the current animation.
  23233. *
  23234. * @method Phaser.AnimationManager#destroy
  23235. */
  23236. destroy: function () {
  23237. this._anims = {};
  23238. this._frameData = null;
  23239. this._frameIndex = 0;
  23240. this.currentAnim = null;
  23241. this.currentFrame = null;
  23242. }
  23243. };
  23244. /**
  23245. * @name Phaser.AnimationManager#frameData
  23246. * @property {Phaser.FrameData} frameData - The current animations FrameData.
  23247. * @readonly
  23248. */
  23249. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', {
  23250. get: function () {
  23251. return this._frameData;
  23252. }
  23253. });
  23254. /**
  23255. * @name Phaser.AnimationManager#frameTotal
  23256. * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
  23257. * @readonly
  23258. */
  23259. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', {
  23260. get: function () {
  23261. if (this._frameData)
  23262. {
  23263. return this._frameData.total;
  23264. }
  23265. else
  23266. {
  23267. return -1;
  23268. }
  23269. }
  23270. });
  23271. /**
  23272. * @name Phaser.AnimationManager#paused
  23273. * @property {boolean} paused - Gets and sets the paused state of the current animation.
  23274. */
  23275. Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', {
  23276. get: function () {
  23277. return this.currentAnim.isPaused;
  23278. },
  23279. set: function (value) {
  23280. this.currentAnim.paused = value;
  23281. }
  23282. });
  23283. /**
  23284. * @name Phaser.AnimationManager#frame
  23285. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  23286. */
  23287. Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', {
  23288. get: function () {
  23289. if (this.currentFrame)
  23290. {
  23291. return this._frameIndex;
  23292. }
  23293. },
  23294. set: function (value) {
  23295. if (typeof value === 'number' && this._frameData && this._frameData.getFrame(value) !== null)
  23296. {
  23297. this.currentFrame = this._frameData.getFrame(value);
  23298. this._frameIndex = value;
  23299. this.sprite.currentFrame = this.currentFrame;
  23300. this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  23301. }
  23302. }
  23303. });
  23304. /**
  23305. * @name Phaser.AnimationManager#frameName
  23306. * @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
  23307. */
  23308. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', {
  23309. get: function () {
  23310. if (this.currentFrame)
  23311. {
  23312. return this.currentFrame.name;
  23313. }
  23314. },
  23315. set: function (value) {
  23316. if (typeof value === 'string' && this._frameData && this._frameData.getFrameByName(value) !== null)
  23317. {
  23318. this.currentFrame = this._frameData.getFrameByName(value);
  23319. this._frameIndex = this.currentFrame.index;
  23320. this.sprite.currentFrame = this.currentFrame;
  23321. this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  23322. }
  23323. else
  23324. {
  23325. console.warn('Cannot set frameName: ' + value);
  23326. }
  23327. }
  23328. });
  23329. /**
  23330. * @author Richard Davey <rich@photonstorm.com>
  23331. * @copyright 2013 Photon Storm Ltd.
  23332. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  23333. */
  23334. /**
  23335. * An Animation instance contains a single animation and the controls to play it.
  23336. * It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite.
  23337. *
  23338. * @class Phaser.Animation
  23339. * @constructor
  23340. * @param {Phaser.Game} game - A reference to the currently running game.
  23341. * @param {Phaser.Sprite} parent - A reference to the owner of this Animation.
  23342. * @param {string} name - The unique name for this animation, used in playback commands.
  23343. * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
  23344. * @param {(Array.<number>|Array.<string>)} frames - An array of numbers or strings indicating which frames to play in which order.
  23345. * @param {number} delay - The time between each frame of the animation, given in ms.
  23346. * @param {boolean} looped - Should this animation loop or play through once.
  23347. */
  23348. Phaser.Animation = function (game, parent, name, frameData, frames, delay, looped) {
  23349. /**
  23350. * @property {Phaser.Game} game - A reference to the currently running Game.
  23351. */
  23352. this.game = game;
  23353. /**
  23354. * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation.
  23355. * @private
  23356. */
  23357. this._parent = parent;
  23358. /**
  23359. * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses.
  23360. * @private
  23361. */
  23362. this._frameData = frameData;
  23363. /**
  23364. * @property {string} name - The user defined name given to this Animation.
  23365. */
  23366. this.name = name;
  23367. /**
  23368. * @property {object} _frames
  23369. * @private
  23370. */
  23371. this._frames = [];
  23372. this._frames = this._frames.concat(frames);
  23373. /**
  23374. * @property {number} delay - The delay in ms between each frame of the Animation.
  23375. */
  23376. this.delay = 1000 / delay;
  23377. /**
  23378. * @property {boolean} looped - The loop state of the Animation.
  23379. */
  23380. this.looped = looped;
  23381. /**
  23382. * @property {boolean} looped - The loop state of the Animation.
  23383. */
  23384. this.killOnComplete = false;
  23385. /**
  23386. * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback.
  23387. * @default
  23388. */
  23389. this.isFinished = false;
  23390. /**
  23391. * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback.
  23392. * @default
  23393. */
  23394. this.isPlaying = false;
  23395. /**
  23396. * @property {boolean} isPaused - The paused state of the Animation.
  23397. * @default
  23398. */
  23399. this.isPaused = false;
  23400. /**
  23401. * @property {boolean} _pauseStartTime - The time the animation paused.
  23402. * @private
  23403. * @default
  23404. */
  23405. this._pauseStartTime = 0;
  23406. /**
  23407. * @property {number} _frameIndex
  23408. * @private
  23409. * @default
  23410. */
  23411. this._frameIndex = 0;
  23412. /**
  23413. * @property {number} _frameDiff
  23414. * @private
  23415. * @default
  23416. */
  23417. this._frameDiff = 0;
  23418. /**
  23419. * @property {number} _frameSkip
  23420. * @private
  23421. * @default
  23422. */
  23423. this._frameSkip = 1;
  23424. /**
  23425. * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation.
  23426. */
  23427. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  23428. };
  23429. Phaser.Animation.prototype = {
  23430. /**
  23431. * Plays this animation.
  23432. *
  23433. * @method Phaser.Animation#play
  23434. * @memberof Phaser.Animation
  23435. * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
  23436. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  23437. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  23438. * @return {Phaser.Animation} - A reference to this Animation instance.
  23439. */
  23440. play: function (frameRate, loop, killOnComplete) {
  23441. if (typeof frameRate === 'number')
  23442. {
  23443. // If they set a new frame rate then use it, otherwise use the one set on creation
  23444. this.delay = 1000 / frameRate;
  23445. }
  23446. if (typeof loop === 'boolean')
  23447. {
  23448. // If they set a new loop value then use it, otherwise use the one set on creation
  23449. this.looped = loop;
  23450. }
  23451. if (typeof killOnComplete !== 'undefined')
  23452. {
  23453. // Remove the parent sprite once the animation has finished?
  23454. this.killOnComplete = killOnComplete;
  23455. }
  23456. this.isPlaying = true;
  23457. this.isFinished = false;
  23458. this.paused = false;
  23459. this._timeLastFrame = this.game.time.now;
  23460. this._timeNextFrame = this.game.time.now + this.delay;
  23461. this._frameIndex = 0;
  23462. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  23463. this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  23464. if (this._parent.events)
  23465. {
  23466. this._parent.events.onAnimationStart.dispatch(this._parent, this);
  23467. }
  23468. return this;
  23469. },
  23470. /**
  23471. * Sets this animation back to the first frame and restarts the animation.
  23472. *
  23473. * @method Phaser.Animation#restart
  23474. * @memberof Phaser.Animation
  23475. */
  23476. restart: function () {
  23477. this.isPlaying = true;
  23478. this.isFinished = false;
  23479. this.paused = false;
  23480. this._timeLastFrame = this.game.time.now;
  23481. this._timeNextFrame = this.game.time.now + this.delay;
  23482. this._frameIndex = 0;
  23483. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  23484. },
  23485. /**
  23486. * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation.
  23487. *
  23488. * @method Phaser.Animation#stop
  23489. * @memberof Phaser.Animation
  23490. * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation.
  23491. */
  23492. stop: function (resetFrame) {
  23493. if (typeof resetFrame === 'undefined') { resetFrame = false; }
  23494. this.isPlaying = false;
  23495. this.isFinished = true;
  23496. this.paused = false;
  23497. if (resetFrame)
  23498. {
  23499. this.currentFrame = this._frameData.getFrame(this._frames[0]);
  23500. }
  23501. },
  23502. /**
  23503. * Updates this animation. Called automatically by the AnimationManager.
  23504. *
  23505. * @method Phaser.Animation#update
  23506. * @memberof Phaser.Animation
  23507. */
  23508. update: function () {
  23509. if (this.isPaused)
  23510. {
  23511. return false;
  23512. }
  23513. if (this.isPlaying === true && this.game.time.now >= this._timeNextFrame)
  23514. {
  23515. this._frameSkip = 1;
  23516. // Lagging?
  23517. this._frameDiff = this.game.time.now - this._timeNextFrame;
  23518. this._timeLastFrame = this.game.time.now;
  23519. if (this._frameDiff > this.delay)
  23520. {
  23521. // We need to skip a frame, work out how many
  23522. this._frameSkip = Math.floor(this._frameDiff / this.delay);
  23523. this._frameDiff -= (this._frameSkip * this.delay);
  23524. }
  23525. // And what's left now?
  23526. this._timeNextFrame = this.game.time.now + (this.delay - this._frameDiff);
  23527. this._frameIndex += this._frameSkip;
  23528. if (this._frameIndex >= this._frames.length)
  23529. {
  23530. if (this.looped)
  23531. {
  23532. this._frameIndex %= this._frames.length;
  23533. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  23534. if (this.currentFrame)
  23535. {
  23536. this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  23537. }
  23538. this._parent.events.onAnimationLoop.dispatch(this._parent, this);
  23539. }
  23540. else
  23541. {
  23542. this.onComplete();
  23543. }
  23544. }
  23545. else
  23546. {
  23547. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  23548. if (this.currentFrame)
  23549. {
  23550. this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  23551. }
  23552. }
  23553. return true;
  23554. }
  23555. return false;
  23556. },
  23557. /**
  23558. * Cleans up this animation ready for deletion. Nulls all values and references.
  23559. *
  23560. * @method Phaser.Animation#destroy
  23561. * @memberof Phaser.Animation
  23562. */
  23563. destroy: function () {
  23564. this.game = null;
  23565. this._parent = null;
  23566. this._frames = null;
  23567. this._frameData = null;
  23568. this.currentFrame = null;
  23569. this.isPlaying = false;
  23570. },
  23571. /**
  23572. * Called internally when the animation finishes playback. Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent.
  23573. *
  23574. * @method Phaser.Animation#onComplete
  23575. * @memberof Phaser.Animation
  23576. */
  23577. onComplete: function () {
  23578. this.isPlaying = false;
  23579. this.isFinished = true;
  23580. this.paused = false;
  23581. if (this._parent.events)
  23582. {
  23583. this._parent.events.onAnimationComplete.dispatch(this._parent, this);
  23584. }
  23585. if (this.killOnComplete)
  23586. {
  23587. this._parent.kill();
  23588. }
  23589. }
  23590. };
  23591. /**
  23592. * @name Phaser.Animation#paused
  23593. * @property {boolean} paused - Gets and sets the paused state of this Animation.
  23594. */
  23595. Object.defineProperty(Phaser.Animation.prototype, 'paused', {
  23596. get: function () {
  23597. return this.isPaused;
  23598. },
  23599. set: function (value) {
  23600. this.isPaused = value;
  23601. if (value)
  23602. {
  23603. // Paused
  23604. this._pauseStartTime = this.game.time.now;
  23605. }
  23606. else
  23607. {
  23608. // Un-paused
  23609. if (this.isPlaying)
  23610. {
  23611. this._timeNextFrame = this.game.time.now + this.delay;
  23612. }
  23613. }
  23614. }
  23615. });
  23616. /**
  23617. * @name Phaser.Animation#frameTotal
  23618. * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
  23619. * @readonly
  23620. */
  23621. Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', {
  23622. get: function () {
  23623. return this._frames.length;
  23624. }
  23625. });
  23626. /**
  23627. * @name Phaser.Animation#frame
  23628. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  23629. */
  23630. Object.defineProperty(Phaser.Animation.prototype, 'frame', {
  23631. get: function () {
  23632. if (this.currentFrame !== null)
  23633. {
  23634. return this.currentFrame.index;
  23635. }
  23636. else
  23637. {
  23638. return this._frameIndex;
  23639. }
  23640. },
  23641. set: function (value) {
  23642. this.currentFrame = this._frameData.getFrame(value);
  23643. if (this.currentFrame !== null)
  23644. {
  23645. this._frameIndex = value;
  23646. this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  23647. }
  23648. }
  23649. });
  23650. /**
  23651. * Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers.
  23652. * For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large'
  23653. * You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4);
  23654. *
  23655. * @method Phaser.Animation.generateFrameNames
  23656. * @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'.
  23657. * @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1.
  23658. * @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34.
  23659. * @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'.
  23660. * @param {number} [zeroPad=0] - The number of zeroes to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4.
  23661. */
  23662. Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) {
  23663. if (typeof suffix == 'undefined') { suffix = ''; }
  23664. var output = [];
  23665. var frame = '';
  23666. if (start < stop)
  23667. {
  23668. for (var i = start; i <= stop; i++)
  23669. {
  23670. if (typeof zeroPad == 'number')
  23671. {
  23672. // str, len, pad, dir
  23673. frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
  23674. }
  23675. else
  23676. {
  23677. frame = i.toString();
  23678. }
  23679. frame = prefix + frame + suffix;
  23680. output.push(frame);
  23681. }
  23682. }
  23683. else
  23684. {
  23685. for (var i = start; i >= stop; i--)
  23686. {
  23687. if (typeof zeroPad == 'number')
  23688. {
  23689. // str, len, pad, dir
  23690. frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
  23691. }
  23692. else
  23693. {
  23694. frame = i.toString();
  23695. }
  23696. frame = prefix + frame + suffix;
  23697. output.push(frame);
  23698. }
  23699. }
  23700. return output;
  23701. }
  23702. /**
  23703. * @author Richard Davey <rich@photonstorm.com>
  23704. * @copyright 2013 Photon Storm Ltd.
  23705. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  23706. */
  23707. /**
  23708. * A Frame is a single frame of an animation and is part of a FrameData collection.
  23709. *
  23710. * @class Phaser.Frame
  23711. * @constructor
  23712. * @param {number} index - The index of this Frame within the FrameData set it is being added to.
  23713. * @param {number} x - X position of the frame within the texture image.
  23714. * @param {number} y - Y position of the frame within the texture image.
  23715. * @param {number} width - Width of the frame within the texture image.
  23716. * @param {number} height - Height of the frame within the texture image.
  23717. * @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename.
  23718. * @param {string} uuid - Internal UUID key.
  23719. */
  23720. Phaser.Frame = function (index, x, y, width, height, name, uuid) {
  23721. /**
  23722. * @property {number} index - The index of this Frame within the FrameData set it is being added to.
  23723. */
  23724. this.index = index;
  23725. /**
  23726. * @property {number} x - X position within the image to cut from.
  23727. */
  23728. this.x = x;
  23729. /**
  23730. * @property {number} y - Y position within the image to cut from.
  23731. */
  23732. this.y = y;
  23733. /**
  23734. * @property {number} width - Width of the frame.
  23735. */
  23736. this.width = width;
  23737. /**
  23738. * @property {number} height - Height of the frame.
  23739. */
  23740. this.height = height;
  23741. /**
  23742. * @property {string} name - Useful for Texture Atlas files (is set to the filename value).
  23743. */
  23744. this.name = name;
  23745. /**
  23746. * @property {string} uuid - A link to the PIXI.TextureCache entry.
  23747. */
  23748. this.uuid = uuid;
  23749. /**
  23750. * @property {number} centerX - Center X position within the image to cut from.
  23751. */
  23752. this.centerX = Math.floor(width / 2);
  23753. /**
  23754. * @property {number} centerY - Center Y position within the image to cut from.
  23755. */
  23756. this.centerY = Math.floor(height / 2);
  23757. /**
  23758. * @property {number} distance - The distance from the top left to the bottom-right of this Frame.
  23759. */
  23760. this.distance = Phaser.Math.distance(0, 0, width, height);
  23761. /**
  23762. * @property {boolean} rotated - Rotated? (not yet implemented)
  23763. * @default
  23764. */
  23765. this.rotated = false;
  23766. /**
  23767. * @property {string} rotationDirection - Either 'cw' or 'ccw', rotation is always 90 degrees.
  23768. * @default 'cw'
  23769. */
  23770. this.rotationDirection = 'cw';
  23771. /**
  23772. * @property {boolean} trimmed - Was it trimmed when packed?
  23773. * @default
  23774. */
  23775. this.trimmed = false;
  23776. /**
  23777. * @property {number} sourceSizeW - Width of the original sprite.
  23778. */
  23779. this.sourceSizeW = width;
  23780. /**
  23781. * @property {number} sourceSizeH - Height of the original sprite.
  23782. */
  23783. this.sourceSizeH = height;
  23784. /**
  23785. * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite.
  23786. * @default
  23787. */
  23788. this.spriteSourceSizeX = 0;
  23789. /**
  23790. * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite.
  23791. * @default
  23792. */
  23793. this.spriteSourceSizeY = 0;
  23794. /**
  23795. * @property {number} spriteSourceSizeW - Width of the trimmed sprite.
  23796. * @default
  23797. */
  23798. this.spriteSourceSizeW = 0;
  23799. /**
  23800. * @property {number} spriteSourceSizeH - Height of the trimmed sprite.
  23801. * @default
  23802. */
  23803. this.spriteSourceSizeH = 0;
  23804. };
  23805. Phaser.Frame.prototype = {
  23806. /**
  23807. * If the frame was trimmed when added to the Texture Atlas this records the trim and source data.
  23808. *
  23809. * @method Phaser.Frame#setTrim
  23810. * @param {boolean} trimmed - If this frame was trimmed or not.
  23811. * @param {number} actualWidth - The width of the frame before being trimmed.
  23812. * @param {number} actualHeight - The height of the frame before being trimmed.
  23813. * @param {number} destX - The destination X position of the trimmed frame for display.
  23814. * @param {number} destY - The destination Y position of the trimmed frame for display.
  23815. * @param {number} destWidth - The destination width of the trimmed frame for display.
  23816. * @param {number} destHeight - The destination height of the trimmed frame for display.
  23817. */
  23818. setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) {
  23819. this.trimmed = trimmed;
  23820. if (trimmed)
  23821. {
  23822. this.width = actualWidth;
  23823. this.height = actualHeight;
  23824. this.sourceSizeW = actualWidth;
  23825. this.sourceSizeH = actualHeight;
  23826. this.centerX = Math.floor(actualWidth / 2);
  23827. this.centerY = Math.floor(actualHeight / 2);
  23828. this.spriteSourceSizeX = destX;
  23829. this.spriteSourceSizeY = destY;
  23830. this.spriteSourceSizeW = destWidth;
  23831. this.spriteSourceSizeH = destHeight;
  23832. }
  23833. }
  23834. };
  23835. /**
  23836. * @author Richard Davey <rich@photonstorm.com>
  23837. * @copyright 2013 Photon Storm Ltd.
  23838. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  23839. */
  23840. /**
  23841. * FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser.
  23842. *
  23843. * @class Phaser.FrameData
  23844. * @constructor
  23845. */
  23846. Phaser.FrameData = function () {
  23847. /**
  23848. * @property {Array} _frames - Local array of frames.
  23849. * @private
  23850. */
  23851. this._frames = [];
  23852. /**
  23853. * @property {Array} _frameNames - Local array of frame names for name to index conversions.
  23854. * @private
  23855. */
  23856. this._frameNames = [];
  23857. };
  23858. Phaser.FrameData.prototype = {
  23859. /**
  23860. * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly.
  23861. *
  23862. * @method Phaser.FrameData#addFrame
  23863. * @param {Phaser.Frame} frame - The frame to add to this FrameData set.
  23864. * @return {Phaser.Frame} The frame that was just added.
  23865. */
  23866. addFrame: function (frame) {
  23867. frame.index = this._frames.length;
  23868. this._frames.push(frame);
  23869. if (frame.name !== '')
  23870. {
  23871. this._frameNames[frame.name] = frame.index;
  23872. }
  23873. return frame;
  23874. },
  23875. /**
  23876. * Get a Frame by its numerical index.
  23877. *
  23878. * @method Phaser.FrameData#getFrame
  23879. * @param {number} index - The index of the frame you want to get.
  23880. * @return {Phaser.Frame} The frame, if found.
  23881. */
  23882. getFrame: function (index) {
  23883. if (this._frames.length > index)
  23884. {
  23885. return this._frames[index];
  23886. }
  23887. return null;
  23888. },
  23889. /**
  23890. * Get a Frame by its frame name.
  23891. *
  23892. * @method Phaser.FrameData#getFrameByName
  23893. * @param {string} name - The name of the frame you want to get.
  23894. * @return {Phaser.Frame} The frame, if found.
  23895. */
  23896. getFrameByName: function (name) {
  23897. if (typeof this._frameNames[name] === 'number')
  23898. {
  23899. return this._frames[this._frameNames[name]];
  23900. }
  23901. return null;
  23902. },
  23903. /**
  23904. * Check if there is a Frame with the given name.
  23905. *
  23906. * @method Phaser.FrameData#checkFrameName
  23907. * @param {string} name - The name of the frame you want to check.
  23908. * @return {boolean} True if the frame is found, otherwise false.
  23909. */
  23910. checkFrameName: function (name) {
  23911. if (this._frameNames[name] == null)
  23912. {
  23913. return false;
  23914. }
  23915. return true;
  23916. },
  23917. /**
  23918. * Returns a range of frames based on the given start and end frame indexes and returns them in an Array.
  23919. *
  23920. * @method Phaser.FrameData#getFrameRange
  23921. * @param {number} start - The starting frame index.
  23922. * @param {number} end - The ending frame index.
  23923. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  23924. * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found.
  23925. */
  23926. getFrameRange: function (start, end, output) {
  23927. if (typeof output === "undefined") { output = []; }
  23928. for (var i = start; i <= end; i++)
  23929. {
  23930. output.push(this._frames[i]);
  23931. }
  23932. return output;
  23933. },
  23934. /**
  23935. * Returns all of the Frames in this FrameData set where the frame index is found in the input array.
  23936. * The frames are returned in the output array, or if none is provided in a new Array object.
  23937. *
  23938. * @method Phaser.FrameData#getFrames
  23939. * @param {Array} frames - An Array containing the indexes of the frames to retrieve. If the array is empty then all frames in the FrameData are returned.
  23940. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
  23941. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  23942. * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs.
  23943. */
  23944. getFrames: function (frames, useNumericIndex, output) {
  23945. if (typeof useNumericIndex === "undefined") { useNumericIndex = true; }
  23946. if (typeof output === "undefined") { output = []; }
  23947. if (typeof frames === "undefined" || frames.length === 0)
  23948. {
  23949. // No input array, so we loop through all frames
  23950. for (var i = 0; i < this._frames.length; i++)
  23951. {
  23952. // We only need the indexes
  23953. output.push(this._frames[i]);
  23954. }
  23955. }
  23956. else
  23957. {
  23958. // Input array given, loop through that instead
  23959. for (var i = 0, len = frames.length; i < len; i++)
  23960. {
  23961. // Does the input array contain names or indexes?
  23962. if (useNumericIndex)
  23963. {
  23964. // The actual frame
  23965. output.push(this.getFrame(frames[i]));
  23966. }
  23967. else
  23968. {
  23969. // The actual frame
  23970. output.push(this.getFrameByName(frames[i]));
  23971. }
  23972. }
  23973. }
  23974. return output;
  23975. },
  23976. /**
  23977. * Returns all of the Frame indexes in this FrameData set.
  23978. * The frames indexes are returned in the output array, or if none is provided in a new Array object.
  23979. *
  23980. * @method Phaser.FrameData#getFrameIndexes
  23981. * @param {Array} frames - An Array containing the indexes of the frames to retrieve. If the array is empty then all frames in the FrameData are returned.
  23982. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
  23983. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  23984. * @return {Array} An array of all Frame indexes matching the given names or IDs.
  23985. */
  23986. getFrameIndexes: function (frames, useNumericIndex, output) {
  23987. if (typeof useNumericIndex === "undefined") { useNumericIndex = true; }
  23988. if (typeof output === "undefined") { output = []; }
  23989. if (typeof frames === "undefined" || frames.length === 0)
  23990. {
  23991. // No frames array, so we loop through all frames
  23992. for (var i = 0, len = this._frames.length; i < len; i++)
  23993. {
  23994. output.push(this._frames[i].index);
  23995. }
  23996. }
  23997. else
  23998. {
  23999. // Input array given, loop through that instead
  24000. for (var i = 0, len = frames.length; i < len; i++)
  24001. {
  24002. // Does the frames array contain names or indexes?
  24003. if (useNumericIndex)
  24004. {
  24005. output.push(frames[i]);
  24006. }
  24007. else
  24008. {
  24009. if (this.getFrameByName(frames[i]))
  24010. {
  24011. output.push(this.getFrameByName(frames[i]).index);
  24012. }
  24013. }
  24014. }
  24015. }
  24016. return output;
  24017. }
  24018. };
  24019. /**
  24020. * @name Phaser.FrameData#total
  24021. * @property {number} total - The total number of frames in this FrameData set.
  24022. * @readonly
  24023. */
  24024. Object.defineProperty(Phaser.FrameData.prototype, "total", {
  24025. get: function () {
  24026. return this._frames.length;
  24027. }
  24028. });
  24029. /**
  24030. * @author Richard Davey <rich@photonstorm.com>
  24031. * @copyright 2013 Photon Storm Ltd.
  24032. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  24033. */
  24034. /**
  24035. * Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations.
  24036. *
  24037. * @class Phaser.AnimationParser
  24038. */
  24039. Phaser.AnimationParser = {
  24040. /**
  24041. * Parse a Sprite Sheet and extract the animation frame data from it.
  24042. *
  24043. * @method Phaser.AnimationParser.spriteSheet
  24044. * @param {Phaser.Game} game - A reference to the currently running game.
  24045. * @param {string} key - The Game.Cache asset key of the Sprite Sheet image.
  24046. * @param {number} frameWidth - The fixed width of each frame of the animation.
  24047. * @param {number} frameHeight - The fixed height of each frame of the animation.
  24048. * @param {number} [frameMax=-1] - The total number of animation frames to extact from the Sprite Sheet. The default value of -1 means "extract all frames".
  24049. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  24050. */
  24051. spriteSheet: function (game, key, frameWidth, frameHeight, frameMax) {
  24052. // How big is our image?
  24053. var img = game.cache.getImage(key);
  24054. if (img == null)
  24055. {
  24056. return null;
  24057. }
  24058. var width = img.width;
  24059. var height = img.height;
  24060. if (frameWidth <= 0)
  24061. {
  24062. frameWidth = Math.floor(-width / Math.min(-1, frameWidth));
  24063. }
  24064. if (frameHeight <= 0)
  24065. {
  24066. frameHeight = Math.floor(-height / Math.min(-1, frameHeight));
  24067. }
  24068. var row = Math.round(width / frameWidth);
  24069. var column = Math.round(height / frameHeight);
  24070. var total = row * column;
  24071. if (frameMax !== -1)
  24072. {
  24073. total = frameMax;
  24074. }
  24075. // Zero or smaller than frame sizes?
  24076. if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0)
  24077. {
  24078. console.warn("Phaser.AnimationParser.spriteSheet: width/height zero or width/height < given frameWidth/frameHeight");
  24079. return null;
  24080. }
  24081. // Let's create some frames then
  24082. var data = new Phaser.FrameData();
  24083. var x = 0;
  24084. var y = 0;
  24085. for (var i = 0; i < total; i++)
  24086. {
  24087. var uuid = game.rnd.uuid();
  24088. data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '', uuid));
  24089. PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[key], {
  24090. x: x,
  24091. y: y,
  24092. width: frameWidth,
  24093. height: frameHeight
  24094. });
  24095. x += frameWidth;
  24096. if (x === width)
  24097. {
  24098. x = 0;
  24099. y += frameHeight;
  24100. }
  24101. }
  24102. return data;
  24103. },
  24104. /**
  24105. * Parse the JSON data and extract the animation frame data from it.
  24106. *
  24107. * @method Phaser.AnimationParser.JSONData
  24108. * @param {Phaser.Game} game - A reference to the currently running game.
  24109. * @param {Object} json - The JSON data from the Texture Atlas. Must be in Array format.
  24110. * @param {string} cacheKey - The Game.Cache asset key of the texture image.
  24111. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  24112. */
  24113. JSONData: function (game, json, cacheKey) {
  24114. // Malformed?
  24115. if (!json['frames'])
  24116. {
  24117. console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array");
  24118. console.log(json);
  24119. return;
  24120. }
  24121. // Let's create some frames then
  24122. var data = new Phaser.FrameData();
  24123. // By this stage frames is a fully parsed array
  24124. var frames = json['frames'];
  24125. var newFrame;
  24126. for (var i = 0; i < frames.length; i++)
  24127. {
  24128. var uuid = game.rnd.uuid();
  24129. newFrame = data.addFrame(new Phaser.Frame(
  24130. i,
  24131. frames[i].frame.x,
  24132. frames[i].frame.y,
  24133. frames[i].frame.w,
  24134. frames[i].frame.h,
  24135. frames[i].filename,
  24136. uuid
  24137. ));
  24138. PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
  24139. x: frames[i].frame.x,
  24140. y: frames[i].frame.y,
  24141. width: frames[i].frame.w,
  24142. height: frames[i].frame.h
  24143. });
  24144. if (frames[i].trimmed)
  24145. {
  24146. newFrame.setTrim(
  24147. frames[i].trimmed,
  24148. frames[i].sourceSize.w,
  24149. frames[i].sourceSize.h,
  24150. frames[i].spriteSourceSize.x,
  24151. frames[i].spriteSourceSize.y,
  24152. frames[i].spriteSourceSize.w,
  24153. frames[i].spriteSourceSize.h
  24154. );
  24155. // We had to hack Pixi to get this to work :(
  24156. PIXI.TextureCache[uuid].trimmed = true;
  24157. PIXI.TextureCache[uuid].trim.x = frames[i].spriteSourceSize.x;
  24158. PIXI.TextureCache[uuid].trim.y = frames[i].spriteSourceSize.y;
  24159. }
  24160. }
  24161. return data;
  24162. },
  24163. /**
  24164. * Parse the JSON data and extract the animation frame data from it.
  24165. *
  24166. * @method Phaser.AnimationParser.JSONDataHash
  24167. * @param {Phaser.Game} game - A reference to the currently running game.
  24168. * @param {Object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format.
  24169. * @param {string} cacheKey - The Game.Cache asset key of the texture image.
  24170. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  24171. */
  24172. JSONDataHash: function (game, json, cacheKey) {
  24173. // Malformed?
  24174. if (!json['frames'])
  24175. {
  24176. console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object");
  24177. console.log(json);
  24178. return;
  24179. }
  24180. // Let's create some frames then
  24181. var data = new Phaser.FrameData();
  24182. // By this stage frames is a fully parsed array
  24183. var frames = json['frames'];
  24184. var newFrame;
  24185. var i = 0;
  24186. for (var key in frames)
  24187. {
  24188. var uuid = game.rnd.uuid();
  24189. newFrame = data.addFrame(new Phaser.Frame(
  24190. i,
  24191. frames[key].frame.x,
  24192. frames[key].frame.y,
  24193. frames[key].frame.w,
  24194. frames[key].frame.h,
  24195. key,
  24196. uuid
  24197. ));
  24198. PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
  24199. x: frames[key].frame.x,
  24200. y: frames[key].frame.y,
  24201. width: frames[key].frame.w,
  24202. height: frames[key].frame.h
  24203. });
  24204. if (frames[key].trimmed)
  24205. {
  24206. newFrame.setTrim(
  24207. frames[key].trimmed,
  24208. frames[key].sourceSize.w,
  24209. frames[key].sourceSize.h,
  24210. frames[key].spriteSourceSize.x,
  24211. frames[key].spriteSourceSize.y,
  24212. frames[key].spriteSourceSize.w,
  24213. frames[key].spriteSourceSize.h
  24214. );
  24215. // We had to hack Pixi to get this to work :(
  24216. PIXI.TextureCache[uuid].trimmed = true;
  24217. PIXI.TextureCache[uuid].trim.x = frames[key].spriteSourceSize.x;
  24218. PIXI.TextureCache[uuid].trim.y = frames[key].spriteSourceSize.y;
  24219. }
  24220. i++;
  24221. }
  24222. return data;
  24223. },
  24224. /**
  24225. * Parse the XML data and extract the animation frame data from it.
  24226. *
  24227. * @method Phaser.AnimationParser.XMLData
  24228. * @param {Phaser.Game} game - A reference to the currently running game.
  24229. * @param {Object} xml - The XML data from the Texture Atlas. Must be in Starling XML format.
  24230. * @param {string} cacheKey - The Game.Cache asset key of the texture image.
  24231. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  24232. */
  24233. XMLData: function (game, xml, cacheKey) {
  24234. // Malformed?
  24235. if (!xml.getElementsByTagName('TextureAtlas'))
  24236. {
  24237. console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");
  24238. return;
  24239. }
  24240. // Let's create some frames then
  24241. var data = new Phaser.FrameData();
  24242. var frames = xml.getElementsByTagName('SubTexture');
  24243. var newFrame;
  24244. var uuid;
  24245. var name;
  24246. var frame;
  24247. var x;
  24248. var y;
  24249. var width;
  24250. var height;
  24251. var frameX;
  24252. var frameY;
  24253. var frameWidth;
  24254. var frameHeight;
  24255. for (var i = 0; i < frames.length; i++)
  24256. {
  24257. uuid = game.rnd.uuid();
  24258. frame = frames[i].attributes;
  24259. name = frame.name.nodeValue;
  24260. x = parseInt(frame.x.nodeValue, 10);
  24261. y = parseInt(frame.y.nodeValue, 10);
  24262. width = parseInt(frame.width.nodeValue, 10);
  24263. height = parseInt(frame.height.nodeValue, 10);
  24264. frameX = null;
  24265. frameY = null;
  24266. if (frame.frameX)
  24267. {
  24268. frameX = Math.abs(parseInt(frame.frameX.nodeValue, 10));
  24269. frameY = Math.abs(parseInt(frame.frameY.nodeValue, 10));
  24270. frameWidth = parseInt(frame.frameWidth.nodeValue, 10);
  24271. frameHeight = parseInt(frame.frameHeight.nodeValue, 10);
  24272. }
  24273. newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name, uuid));
  24274. PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
  24275. x: x,
  24276. y: y,
  24277. width: width,
  24278. height: height
  24279. });
  24280. // Trimmed?
  24281. if (frameX !== null || frameY !== null)
  24282. {
  24283. newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight);
  24284. PIXI.TextureCache[uuid].realSize = { x: frameX, y: frameY, w: frameWidth, h: frameHeight };
  24285. // We had to hack Pixi to get this to work :(
  24286. PIXI.TextureCache[uuid].trimmed = true;
  24287. PIXI.TextureCache[uuid].trim.x = frameX;
  24288. PIXI.TextureCache[uuid].trim.y = frameY;
  24289. }
  24290. }
  24291. return data;
  24292. }
  24293. };
  24294. /**
  24295. * @author Richard Davey <rich@photonstorm.com>
  24296. * @copyright 2013 Photon Storm Ltd.
  24297. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  24298. */
  24299. /**
  24300. * Phaser.Cache constructor.
  24301. *
  24302. * @class Phaser.Cache
  24303. * @classdesc A game only has one instance of a Cache and it is used to store all externally loaded assets such
  24304. * as images, sounds and data files as a result of Loader calls. Cache items use string based keys for look-up.
  24305. * @constructor
  24306. * @param {Phaser.Game} game - A reference to the currently running game.
  24307. */
  24308. Phaser.Cache = function (game) {
  24309. /**
  24310. * @property {Phaser.Game} game - Local reference to game.
  24311. */
  24312. this.game = game;
  24313. /**
  24314. * @property {object} game - Canvas key-value container.
  24315. * @private
  24316. */
  24317. this._canvases = {};
  24318. /**
  24319. * @property {object} _images - Image key-value container.
  24320. * @private
  24321. */
  24322. this._images = {};
  24323. /**
  24324. * @property {object} _textures - RenderTexture key-value container.
  24325. * @private
  24326. */
  24327. this._textures = {};
  24328. /**
  24329. * @property {object} _sounds - Sound key-value container.
  24330. * @private
  24331. */
  24332. this._sounds = {};
  24333. /**
  24334. * @property {object} _text - Text key-value container.
  24335. * @private
  24336. */
  24337. this._text = {};
  24338. /**
  24339. * @property {object} _tilemaps - Tilemap key-value container.
  24340. * @private
  24341. */
  24342. this._tilemaps = {};
  24343. /**
  24344. * @property {object} _tilesets - Tileset key-value container.
  24345. * @private
  24346. */
  24347. this._tilesets = {};
  24348. /**
  24349. * @property {object} _bitmapDatas - BitmapData key-value container.
  24350. * @private
  24351. */
  24352. this._bitmapDatas = {};
  24353. this.addDefaultImage();
  24354. this.addMissingImage();
  24355. /**
  24356. * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices.
  24357. */
  24358. this.onSoundUnlock = new Phaser.Signal();
  24359. };
  24360. Phaser.Cache.prototype = {
  24361. /**
  24362. * Add a new canvas object in to the cache.
  24363. * @method Phaser.Cache#addCanvas
  24364. * @param {string} key - Asset key for this canvas.
  24365. * @param {HTMLCanvasElement} canvas - Canvas DOM element.
  24366. * @param {CanvasRenderingContext2D} context - Render context of this canvas.
  24367. */
  24368. addCanvas: function (key, canvas, context) {
  24369. this._canvases[key] = { canvas: canvas, context: context };
  24370. },
  24371. /**
  24372. * Add a BitmapData object in to the cache.
  24373. * @method Phaser.Cache#addBitmapData
  24374. * @param {string} key - Asset key for this BitmapData.
  24375. * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache.
  24376. * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache.
  24377. */
  24378. addBitmapData: function (key, bitmapData) {
  24379. this._bitmapDatas[key] = bitmapData;
  24380. return bitmapData;
  24381. },
  24382. /**
  24383. * Add a new Phaser.RenderTexture in to the cache.
  24384. *
  24385. * @method Phaser.Cache#addRenderTexture
  24386. * @param {string} key - The unique key by which you will reference this object.
  24387. * @param {Phaser.Texture} texture - The texture to use as the base of the RenderTexture.
  24388. */
  24389. addRenderTexture: function (key, texture) {
  24390. var frame = new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '');
  24391. this._textures[key] = { texture: texture, frame: frame };
  24392. },
  24393. /**
  24394. * Add a new sprite sheet in to the cache.
  24395. *
  24396. * @method Phaser.Cache#addSpriteSheet
  24397. * @param {string} key - The unique key by which you will reference this object.
  24398. * @param {string} url - URL of this sprite sheet file.
  24399. * @param {object} data - Extra sprite sheet data.
  24400. * @param {number} frameWidth - Width of the sprite sheet.
  24401. * @param {number} frameHeight - Height of the sprite sheet.
  24402. * @param {number} frameMax - How many frames stored in the sprite sheet.
  24403. */
  24404. addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax) {
  24405. this._images[key] = { url: url, data: data, spriteSheet: true, frameWidth: frameWidth, frameHeight: frameHeight };
  24406. PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
  24407. PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
  24408. this._images[key].frameData = Phaser.AnimationParser.spriteSheet(this.game, key, frameWidth, frameHeight, frameMax);
  24409. },
  24410. /**
  24411. * Add a new tile set in to the cache.
  24412. *
  24413. * @method Phaser.Cache#addTileset
  24414. * @param {string} key - The unique key by which you will reference this object.
  24415. * @param {string} url - URL of this tile set file.
  24416. * @param {object} data - Extra tile set data.
  24417. * @param {number} tileWidth - Width of the sprite sheet.
  24418. * @param {number} tileHeight - Height of the sprite sheet.
  24419. * @param {number} tileMax - How many tiles stored in the sprite sheet.
  24420. * @param {number} [tileMargin=0] - If the tiles have been drawn with a margin, specify the amount here.
  24421. * @param {number} [tileSpacing=0] - If the tiles have been drawn with spacing between them, specify the amount here.
  24422. */
  24423. addTileset: function (key, url, data, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing) {
  24424. this._tilesets[key] = { url: url, data: data, tileWidth: tileWidth, tileHeight: tileHeight, tileMargin: tileMargin, tileSpacing: tileSpacing };
  24425. PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
  24426. PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
  24427. this._tilesets[key].tileData = Phaser.TilemapParser.tileset(this.game, key, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing);
  24428. },
  24429. /**
  24430. * Add a new tilemap.
  24431. *
  24432. * @method Phaser.Cache#addTilemap
  24433. * @param {string} key - The unique key by which you will reference this object.
  24434. * @param {string} url - URL of the tilemap image.
  24435. * @param {object} mapData - The tilemap data object.
  24436. * @param {number} format - The format of the tilemap data.
  24437. */
  24438. addTilemap: function (key, url, mapData, format) {
  24439. this._tilemaps[key] = { url: url, data: mapData, format: format };
  24440. this._tilemaps[key].layers = Phaser.TilemapParser.parse(this.game, mapData, format);
  24441. },
  24442. /**
  24443. * Add a new texture atlas.
  24444. *
  24445. * @method Phaser.Cache#addTextureAtlas
  24446. * @param {string} key - The unique key by which you will reference this object.
  24447. * @param {string} url - URL of this texture atlas file.
  24448. * @param {object} data - Extra texture atlas data.
  24449. * @param {object} atlasData - Texture atlas frames data.
  24450. * @param {number} format - The format of the texture atlas.
  24451. */
  24452. addTextureAtlas: function (key, url, data, atlasData, format) {
  24453. this._images[key] = { url: url, data: data, spriteSheet: true };
  24454. PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
  24455. PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
  24456. if (format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY)
  24457. {
  24458. this._images[key].frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key);
  24459. }
  24460. else if (format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH)
  24461. {
  24462. this._images[key].frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key);
  24463. }
  24464. else if (format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
  24465. {
  24466. this._images[key].frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key);
  24467. }
  24468. },
  24469. /**
  24470. * Add a new Bitmap Font.
  24471. *
  24472. * @method Phaser.Cache#addBitmapFont
  24473. * @param {string} key - The unique key by which you will reference this object.
  24474. * @param {string} url - URL of this font xml file.
  24475. * @param {object} data - Extra font data.
  24476. * @param xmlData {object} Texture atlas frames data.
  24477. */
  24478. addBitmapFont: function (key, url, data, xmlData) {
  24479. this._images[key] = { url: url, data: data, spriteSheet: true };
  24480. PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
  24481. PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
  24482. Phaser.LoaderParser.bitmapFont(this.game, xmlData, key);
  24483. // this._images[key].frameData = Phaser.AnimationParser.XMLData(this.game, xmlData, key);
  24484. },
  24485. /**
  24486. * Adds a default image to be used in special cases such as WebGL Filters. Is mapped to the key __default.
  24487. *
  24488. * @method Phaser.Cache#addDefaultImage
  24489. */
  24490. addDefaultImage: function () {
  24491. var img = new Image();
  24492. img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";
  24493. this._images['__default'] = { url: null, data: img, spriteSheet: false };
  24494. this._images['__default'].frame = new Phaser.Frame(0, 0, 0, 32, 32, '', '');
  24495. PIXI.BaseTextureCache['__default'] = new PIXI.BaseTexture(img);
  24496. PIXI.TextureCache['__default'] = new PIXI.Texture(PIXI.BaseTextureCache['__default']);
  24497. },
  24498. /**
  24499. * Adds an image to be used when a key is wrong / missing. Is mapped to the key __missing.
  24500. *
  24501. * @method Phaser.Cache#addMissingImage
  24502. */
  24503. addMissingImage: function () {
  24504. var img = new Image();
  24505. img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";
  24506. this._images['__missing'] = { url: null, data: img, spriteSheet: false };
  24507. this._images['__missing'].frame = new Phaser.Frame(0, 0, 0, 32, 32, '', '');
  24508. PIXI.BaseTextureCache['__missing'] = new PIXI.BaseTexture(img);
  24509. PIXI.TextureCache['__missing'] = new PIXI.Texture(PIXI.BaseTextureCache['__missing']);
  24510. },
  24511. /**
  24512. * Add a new text data.
  24513. *
  24514. * @method Phaser.Cache#addText
  24515. * @param {string} key - Asset key for the text data.
  24516. * @param {string} url - URL of this text data file.
  24517. * @param {object} data - Extra text data.
  24518. */
  24519. addText: function (key, url, data) {
  24520. this._text[key] = {
  24521. url: url,
  24522. data: data
  24523. };
  24524. },
  24525. /**
  24526. * Add a new image.
  24527. *
  24528. * @method Phaser.Cache#addImage
  24529. * @param {string} key - The unique key by which you will reference this object.
  24530. * @param {string} url - URL of this image file.
  24531. * @param {object} data - Extra image data.
  24532. */
  24533. addImage: function (key, url, data) {
  24534. this._images[key] = { url: url, data: data, spriteSheet: false };
  24535. this._images[key].frame = new Phaser.Frame(0, 0, 0, data.width, data.height, key, this.game.rnd.uuid());
  24536. PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
  24537. PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
  24538. },
  24539. /**
  24540. * Add a new sound.
  24541. *
  24542. * @method Phaser.Cache#addSound
  24543. * @param {string} key - Asset key for the sound.
  24544. * @param {string} url - URL of this sound file.
  24545. * @param {object} data - Extra sound data.
  24546. * @param {boolean} webAudio - True if the file is using web audio.
  24547. * @param {boolean} audioTag - True if the file is using legacy HTML audio.
  24548. */
  24549. addSound: function (key, url, data, webAudio, audioTag) {
  24550. webAudio = webAudio || true;
  24551. audioTag = audioTag || false;
  24552. var decoded = false;
  24553. if (audioTag)
  24554. {
  24555. decoded = true;
  24556. }
  24557. this._sounds[key] = { url: url, data: data, isDecoding: false, decoded: decoded, webAudio: webAudio, audioTag: audioTag };
  24558. },
  24559. /**
  24560. * Reload a sound.
  24561. * @method Phaser.Cache#reloadSound
  24562. * @param {string} key - Asset key for the sound.
  24563. */
  24564. reloadSound: function (key) {
  24565. var _this = this;
  24566. if (this._sounds[key])
  24567. {
  24568. this._sounds[key].data.src = this._sounds[key].url;
  24569. this._sounds[key].data.addEventListener('canplaythrough', function () {
  24570. return _this.reloadSoundComplete(key);
  24571. }, false);
  24572. this._sounds[key].data.load();
  24573. }
  24574. },
  24575. /**
  24576. * Description.
  24577. * @method Phaser.Cache#reloadSoundComplete
  24578. * @param {string} key - Asset key for the sound.
  24579. */
  24580. reloadSoundComplete: function (key) {
  24581. if (this._sounds[key])
  24582. {
  24583. this._sounds[key].locked = false;
  24584. this.onSoundUnlock.dispatch(key);
  24585. }
  24586. },
  24587. /**
  24588. * Description.
  24589. * @method Phaser.Cache#updateSound
  24590. * @param {string} key - Asset key for the sound.
  24591. */
  24592. updateSound: function (key, property, value) {
  24593. if (this._sounds[key])
  24594. {
  24595. this._sounds[key][property] = value;
  24596. }
  24597. },
  24598. /**
  24599. * Add a new decoded sound.
  24600. *
  24601. * @method Phaser.Cache#decodedSound
  24602. * @param {string} key - Asset key for the sound.
  24603. * @param {object} data - Extra sound data.
  24604. */
  24605. decodedSound: function (key, data) {
  24606. this._sounds[key].data = data;
  24607. this._sounds[key].decoded = true;
  24608. this._sounds[key].isDecoding = false;
  24609. },
  24610. /**
  24611. * Get a canvas object from the cache by its key.
  24612. *
  24613. * @method Phaser.Cache#getCanvas
  24614. * @param {string} key - Asset key of the canvas you want.
  24615. * @return {object} The canvas you want.
  24616. */
  24617. getCanvas: function (key) {
  24618. if (this._canvases[key])
  24619. {
  24620. return this._canvases[key].canvas;
  24621. }
  24622. return null;
  24623. },
  24624. /**
  24625. * Get a BitmapData object from the cache by its key.
  24626. *
  24627. * @method Phaser.Cache#getBitmapData
  24628. * @param {string} key - Asset key of the BitmapData object you want.
  24629. * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not.
  24630. */
  24631. getBitmapData: function (key) {
  24632. if (this._bitmapDatas[key])
  24633. {
  24634. return this._bitmapDatas[key];
  24635. }
  24636. return null;
  24637. },
  24638. /**
  24639. * Checks if an image key exists.
  24640. *
  24641. * @method Phaser.Cache#checkImageKey
  24642. * @param {string} key - Asset key of the image you want.
  24643. * @return {boolean} True if the key exists, otherwise false.
  24644. */
  24645. checkImageKey: function (key) {
  24646. if (this._images[key])
  24647. {
  24648. return true;
  24649. }
  24650. return false;
  24651. },
  24652. /**
  24653. * Get image data by key.
  24654. *
  24655. * @method Phaser.Cache#getImage
  24656. * @param {string} key - Asset key of the image you want.
  24657. * @return {object} The image data you want.
  24658. */
  24659. getImage: function (key) {
  24660. if (this._images[key])
  24661. {
  24662. return this._images[key].data;
  24663. }
  24664. return null;
  24665. },
  24666. /**
  24667. * Get tile set image data by key.
  24668. *
  24669. * @method Phaser.Cache#getTileSetImage
  24670. * @param {string} key - Asset key of the image you want.
  24671. * @return {object} The image data you want.
  24672. */
  24673. getTilesetImage: function (key) {
  24674. if (this._tilesets[key])
  24675. {
  24676. return this._tilesets[key].data;
  24677. }
  24678. return null;
  24679. },
  24680. /**
  24681. * Get tile set image data by key.
  24682. *
  24683. * @method Phaser.Cache#getTileset
  24684. * @param {string} key - Asset key of the image you want.
  24685. * @return {Phaser.Tileset} The tileset data. The tileset image is in the data property, the tile data in tileData.
  24686. */
  24687. getTileset: function (key) {
  24688. if (this._tilesets[key])
  24689. {
  24690. return this._tilesets[key].tileData;
  24691. }
  24692. return null;
  24693. },
  24694. /**
  24695. * Get tilemap data by key.
  24696. *
  24697. * @method Phaser.Cache#getTilemap
  24698. * @param {string} key - Asset key of the tilemap you want.
  24699. * @return {Object} The tilemap data. The tileset image is in the data property, the map data in mapData.
  24700. */
  24701. getTilemapData: function (key) {
  24702. if (this._tilemaps[key])
  24703. {
  24704. return this._tilemaps[key];
  24705. }
  24706. return null;
  24707. },
  24708. /**
  24709. * Get frame data by key.
  24710. *
  24711. * @method Phaser.Cache#getFrameData
  24712. * @param {string} key - Asset key of the frame data you want.
  24713. * @return {Phaser.FrameData} The frame data you want.
  24714. */
  24715. getFrameData: function (key) {
  24716. if (this._images[key] && this._images[key].frameData)
  24717. {
  24718. return this._images[key].frameData;
  24719. }
  24720. return null;
  24721. },
  24722. /**
  24723. * Get a single frame out of a frameData set by key.
  24724. *
  24725. * @method Phaser.Cache#getFrameByIndex
  24726. * @param {string} key - Asset key of the frame data you want.
  24727. * @return {Phaser.Frame} The frame data you want.
  24728. */
  24729. getFrameByIndex: function (key, frame) {
  24730. if (this._images[key] && this._images[key].frameData)
  24731. {
  24732. return this._images[key].frameData.getFrame(frame);
  24733. }
  24734. return null;
  24735. },
  24736. /**
  24737. * Get a single frame out of a frameData set by key.
  24738. *
  24739. * @method Phaser.Cache#getFrameByName
  24740. * @param {string} key - Asset key of the frame data you want.
  24741. * @return {Phaser.Frame} The frame data you want.
  24742. */
  24743. getFrameByName: function (key, frame) {
  24744. if (this._images[key] && this._images[key].frameData)
  24745. {
  24746. return this._images[key].frameData.getFrameByName(frame);
  24747. }
  24748. return null;
  24749. },
  24750. /**
  24751. * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.
  24752. *
  24753. * @method Phaser.Cache#getFrame
  24754. * @param {string} key - Asset key of the frame data you want.
  24755. * @return {Phaser.Frame} The frame data you want.
  24756. */
  24757. getFrame: function (key) {
  24758. if (this._images[key] && this._images[key].spriteSheet === false)
  24759. {
  24760. return this._images[key].frame;
  24761. }
  24762. return null;
  24763. },
  24764. /**
  24765. * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.
  24766. *
  24767. * @method Phaser.Cache#getTextureFrame
  24768. * @param {string} key - Asset key of the frame data you want.
  24769. * @return {Phaser.Frame} The frame data you want.
  24770. */
  24771. getTextureFrame: function (key) {
  24772. if (this._textures[key])
  24773. {
  24774. return this._textures[key].frame;
  24775. }
  24776. return null;
  24777. },
  24778. /**
  24779. * Get a RenderTexture by key.
  24780. *
  24781. * @method Phaser.Cache#getTexture
  24782. * @param {string} key - Asset key of the RenderTexture you want.
  24783. * @return {Phaser.RenderTexture} The RenderTexture you want.
  24784. */
  24785. getTexture: function (key) {
  24786. if (this._textures[key])
  24787. {
  24788. return this._textures[key];
  24789. }
  24790. return null;
  24791. },
  24792. /**
  24793. * Get sound by key.
  24794. *
  24795. * @method Phaser.Cache#getSound
  24796. * @param {string} key - Asset key of the sound you want.
  24797. * @return {Phaser.Sound} The sound you want.
  24798. */
  24799. getSound: function (key) {
  24800. if (this._sounds[key])
  24801. {
  24802. return this._sounds[key];
  24803. }
  24804. return null;
  24805. },
  24806. /**
  24807. * Get sound data by key.
  24808. *
  24809. * @method Phaser.Cache#getSoundData
  24810. * @param {string} key - Asset key of the sound you want.
  24811. * @return {object} The sound data you want.
  24812. */
  24813. getSoundData: function (key) {
  24814. if (this._sounds[key])
  24815. {
  24816. return this._sounds[key].data;
  24817. }
  24818. return null;
  24819. },
  24820. /**
  24821. * Check if the given sound has finished decoding.
  24822. *
  24823. * @method Phaser.Cache#isSoundDecoded
  24824. * @param {string} key - Asset key of the sound you want.
  24825. * @return {boolean} The decoded state of the Sound object.
  24826. */
  24827. isSoundDecoded: function (key) {
  24828. if (this._sounds[key])
  24829. {
  24830. return this._sounds[key].decoded;
  24831. }
  24832. },
  24833. /**
  24834. * Check if the given sound is ready for playback. A sound is considered ready when it has finished decoding and the device is no longer touch locked.
  24835. *
  24836. * @method Phaser.Cache#isSoundReady
  24837. * @param {string} key - Asset key of the sound you want.
  24838. * @return {boolean} True if the sound is decoded and the device is not touch locked.
  24839. */
  24840. isSoundReady: function (key) {
  24841. return (this._sounds[key] && this._sounds[key].decoded && this.game.sound.touchLocked === false);
  24842. },
  24843. /**
  24844. * Check whether an image asset is sprite sheet or not.
  24845. *
  24846. * @method Phaser.Cache#isSpriteSheet
  24847. * @param {string} key - Asset key of the sprite sheet you want.
  24848. * @return {boolean} True if the image is a sprite sheet.
  24849. */
  24850. isSpriteSheet: function (key) {
  24851. if (this._images[key])
  24852. {
  24853. return this._images[key].spriteSheet;
  24854. }
  24855. return false;
  24856. },
  24857. /**
  24858. * Get text data by key.
  24859. *
  24860. * @method Phaser.Cache#getText
  24861. * @param {string} key - Asset key of the text data you want.
  24862. * @return {object} The text data you want.
  24863. */
  24864. getText: function (key) {
  24865. if (this._text[key])
  24866. {
  24867. return this._text[key].data;
  24868. }
  24869. return null;
  24870. },
  24871. /**
  24872. * Get the cache keys from a given array of objects.
  24873. * Normally you don't call this directly but instead use getImageKeys, getSoundKeys, etc.
  24874. *
  24875. * @method Phaser.Cache#getKeys
  24876. * @param {Array} array - An array of items to return the keys for.
  24877. * @return {Array} The array of item keys.
  24878. */
  24879. getKeys: function (array) {
  24880. var output = [];
  24881. for (var item in array)
  24882. {
  24883. if (item !== '__default')
  24884. {
  24885. output.push(item);
  24886. }
  24887. }
  24888. return output;
  24889. },
  24890. /**
  24891. * Returns an array containing all of the keys of Images in the Cache.
  24892. *
  24893. * @method Phaser.Cache#getImageKeys
  24894. * @return {Array} The string based keys in the Cache.
  24895. */
  24896. getImageKeys: function () {
  24897. return this.getKeys(this._images);
  24898. },
  24899. /**
  24900. * Returns an array containing all of the keys of Sounds in the Cache.
  24901. *
  24902. * @method Phaser.Cache#getSoundKeys
  24903. * @return {Array} The string based keys in the Cache.
  24904. */
  24905. getSoundKeys: function () {
  24906. return this.getKeys(this._sounds);
  24907. },
  24908. /**
  24909. * Returns an array containing all of the keys of Text Files in the Cache.
  24910. *
  24911. * @method Phaser.Cache#getTextKeys
  24912. * @return {Array} The string based keys in the Cache.
  24913. */
  24914. getTextKeys: function () {
  24915. return this.getKeys(this._text);
  24916. },
  24917. /**
  24918. * Removes a canvas from the cache.
  24919. *
  24920. * @method Phaser.Cache#removeCanvas
  24921. * @param {string} key - Key of the asset you want to remove.
  24922. */
  24923. removeCanvas: function (key) {
  24924. delete this._canvases[key];
  24925. },
  24926. /**
  24927. * Removes an image from the cache.
  24928. *
  24929. * @method Phaser.Cache#removeImage
  24930. * @param {string} key - Key of the asset you want to remove.
  24931. */
  24932. removeImage: function (key) {
  24933. delete this._images[key];
  24934. },
  24935. /**
  24936. * Removes a sound from the cache.
  24937. *
  24938. * @method Phaser.Cache#removeSound
  24939. * @param {string} key - Key of the asset you want to remove.
  24940. */
  24941. removeSound: function (key) {
  24942. delete this._sounds[key];
  24943. },
  24944. /**
  24945. * Removes a text from the cache.
  24946. *
  24947. * @method Phaser.Cache#removeText
  24948. * @param {string} key - Key of the asset you want to remove.
  24949. */
  24950. removeText: function (key) {
  24951. delete this._text[key];
  24952. },
  24953. /**
  24954. * Clears the cache. Removes every local cache object reference.
  24955. *
  24956. * @method Phaser.Cache#destroy
  24957. */
  24958. destroy: function () {
  24959. for (var item in this._canvases)
  24960. {
  24961. delete this._canvases[item['key']];
  24962. }
  24963. for (var item in this._images)
  24964. {
  24965. delete this._images[item['key']];
  24966. }
  24967. for (var item in this._sounds)
  24968. {
  24969. delete this._sounds[item['key']];
  24970. }
  24971. for (var item in this._text)
  24972. {
  24973. delete this._text[item['key']];
  24974. }
  24975. }
  24976. };
  24977. /**
  24978. * @author Richard Davey <rich@photonstorm.com>
  24979. * @copyright 2013 Photon Storm Ltd.
  24980. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  24981. */
  24982. /**
  24983. * Phaser loader constructor.
  24984. * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
  24985. * It uses a combination of Image() loading and xhr and provides progress and completion callbacks.
  24986. * @class Phaser.Loader
  24987. * @classdesc The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
  24988. * It uses a combination of Image() loading and xhr and provides progress and completion callbacks.
  24989. * @constructor
  24990. * @param {Phaser.Game} game - A reference to the currently running game.
  24991. */
  24992. Phaser.Loader = function (game) {
  24993. /**
  24994. * @property {Phaser.Game} game - Local reference to game.
  24995. */
  24996. this.game = game;
  24997. /**
  24998. * @property {array} _fileList - Contains all the assets file infos.
  24999. * @private
  25000. */
  25001. this._fileList = [];
  25002. /**
  25003. * @property {number} _fileIndex - The index of the current file being loaded.
  25004. * @private
  25005. */
  25006. this._fileIndex = 0;
  25007. /**
  25008. * @property {number} _progressChunk - Indicates assets loading progress. (from 0 to 100)
  25009. * @private
  25010. * @default
  25011. */
  25012. this._progressChunk = 0;
  25013. /**
  25014. * @property {XMLHttpRequest} - An XMLHttpRequest object used for loading text and audio data.
  25015. * @private
  25016. */
  25017. this._xhr = new XMLHttpRequest();
  25018. /**
  25019. * @property {boolean} isLoading - True if the Loader is in the process of loading the queue.
  25020. * @default
  25021. */
  25022. this.isLoading = false;
  25023. /**
  25024. * @property {boolean} hasLoaded - True if all assets in the queue have finished loading.
  25025. * @default
  25026. */
  25027. this.hasLoaded = false;
  25028. /**
  25029. * @property {number} progress - The Load progress percentage value (from 0 to 100)
  25030. * @default
  25031. */
  25032. this.progress = 0;
  25033. /**
  25034. * You can optionally link a sprite to the preloader.
  25035. * If you do so the Sprite's width or height will be cropped based on the percentage loaded.
  25036. * @property {Phaser.Sprite} preloadSprite
  25037. * @default
  25038. */
  25039. this.preloadSprite = null;
  25040. /**
  25041. * @property {string} crossOrigin - The crossOrigin value applied to loaded images
  25042. */
  25043. this.crossOrigin = '';
  25044. /**
  25045. * If you want to append a URL before the path of any asset you can set this here.
  25046. * Useful if you need to allow an asset url to be configured outside of the game code.
  25047. * MUST have / on the end of it!
  25048. * @property {string} baseURL
  25049. * @default
  25050. */
  25051. this.baseURL = '';
  25052. /**
  25053. * @property {Phaser.Signal} onFileComplete - Event signal.
  25054. */
  25055. this.onFileComplete = new Phaser.Signal();
  25056. /**
  25057. * @property {Phaser.Signal} onFileError - Event signal.
  25058. */
  25059. this.onFileError = new Phaser.Signal();
  25060. /**
  25061. * @property {Phaser.Signal} onLoadStart - Event signal.
  25062. */
  25063. this.onLoadStart = new Phaser.Signal();
  25064. /**
  25065. * @property {Phaser.Signal} onLoadComplete - Event signal.
  25066. */
  25067. this.onLoadComplete = new Phaser.Signal();
  25068. };
  25069. /**
  25070. * @constant
  25071. * @type {number}
  25072. */
  25073. Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0;
  25074. /**
  25075. * @constant
  25076. * @type {number}
  25077. */
  25078. Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1;
  25079. /**
  25080. * @constant
  25081. * @type {number}
  25082. */
  25083. Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2;
  25084. Phaser.Loader.prototype = {
  25085. /**
  25086. * You can set a Sprite to be a "preload" sprite by passing it to this method.
  25087. * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time.
  25088. * This allows you to easily make loading bars for games.
  25089. *
  25090. * @method Phaser.Loader#setPreloadSprite
  25091. * @param {Phaser.Sprite} sprite - The sprite that will be cropped during the load.
  25092. * @param {number} [direction=0] - A value of zero means the sprite width will be cropped, a value of 1 means its height will be cropped.
  25093. */
  25094. setPreloadSprite: function (sprite, direction) {
  25095. direction = direction || 0;
  25096. this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, crop: null };
  25097. if (direction === 0)
  25098. {
  25099. // Horizontal crop
  25100. this.preloadSprite.crop = new Phaser.Rectangle(0, 0, 1, sprite.height);
  25101. }
  25102. else
  25103. {
  25104. // Vertical crop
  25105. this.preloadSprite.crop = new Phaser.Rectangle(0, 0, sprite.width, 1);
  25106. }
  25107. sprite.crop = this.preloadSprite.crop;
  25108. sprite.cropEnabled = true;
  25109. },
  25110. /**
  25111. * Check whether asset exists with a specific key.
  25112. *
  25113. * @method Phaser.Loader#checkKeyExists
  25114. * @param {string} type - The type asset you want to check.
  25115. * @param {string} key - Key of the asset you want to check.
  25116. * @return {boolean} Return true if exists, otherwise return false.
  25117. */
  25118. checkKeyExists: function (type, key) {
  25119. if (this._fileList.length > 0)
  25120. {
  25121. for (var i = 0; i < this._fileList.length; i++)
  25122. {
  25123. if (this._fileList[i].type === type && this._fileList[i].key === key)
  25124. {
  25125. return true;
  25126. }
  25127. }
  25128. }
  25129. return false;
  25130. },
  25131. /**
  25132. * Gets the asset that is queued for load.
  25133. *
  25134. * @method Phaser.Loader#getAsset
  25135. * @param {string} type - The type asset you want to check.
  25136. * @param {string} key - Key of the asset you want to check.
  25137. * @return {any} Returns an object if found that has 2 properties: index and file. Otherwise false.
  25138. */
  25139. getAsset: function (type, key) {
  25140. if (this._fileList.length > 0)
  25141. {
  25142. for (var i = 0; i < this._fileList.length; i++)
  25143. {
  25144. if (this._fileList[i].type === type && this._fileList[i].key === key)
  25145. {
  25146. return { index: i, file: this._fileList[i] };
  25147. }
  25148. }
  25149. }
  25150. return false;
  25151. },
  25152. /**
  25153. * Reset loader, this will remove the load queue.
  25154. *
  25155. * @method Phaser.Loader#reset
  25156. */
  25157. reset: function () {
  25158. this.preloadSprite = null;
  25159. this.isLoading = false;
  25160. this._fileList.length = 0;
  25161. this._fileIndex = 0;
  25162. },
  25163. /**
  25164. * Internal function that adds a new entry to the file list. Do not call directly.
  25165. *
  25166. * @method Phaser.Loader#addToFileList
  25167. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  25168. * @param {string} key - The unique Cache ID key of this resource.
  25169. * @param {string} url - The URL the asset will be loaded from.
  25170. * @param {object} properties - Any additional properties needed to load the file.
  25171. * @protected
  25172. */
  25173. addToFileList: function (type, key, url, properties) {
  25174. var entry = {
  25175. type: type,
  25176. key: key,
  25177. url: url,
  25178. data: null,
  25179. error: false,
  25180. loaded: false
  25181. };
  25182. if (typeof properties !== "undefined")
  25183. {
  25184. for (var prop in properties)
  25185. {
  25186. entry[prop] = properties[prop];
  25187. }
  25188. }
  25189. if (this.checkKeyExists(type, key) === false)
  25190. {
  25191. this._fileList.push(entry);
  25192. }
  25193. },
  25194. /**
  25195. * Internal function that replaces an existing entry in the file list with a new one. Do not call directly.
  25196. *
  25197. * @method Phaser.Loader#replaceInFileList
  25198. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  25199. * @param {string} key - The unique Cache ID key of this resource.
  25200. * @param {string} url - The URL the asset will be loaded from.
  25201. * @param {object} properties - Any additional properties needed to load the file.
  25202. * @protected
  25203. */
  25204. replaceInFileList: function (type, key, url, properties) {
  25205. var entry = {
  25206. type: type,
  25207. key: key,
  25208. url: url,
  25209. data: null,
  25210. error: false,
  25211. loaded: false
  25212. };
  25213. if (typeof properties !== "undefined")
  25214. {
  25215. for (var prop in properties)
  25216. {
  25217. entry[prop] = properties[prop];
  25218. }
  25219. }
  25220. if (this.checkKeyExists(type, key) === false)
  25221. {
  25222. this._fileList.push(entry);
  25223. }
  25224. },
  25225. /**
  25226. * Add an image to the Loader.
  25227. *
  25228. * @method Phaser.Loader#image
  25229. * @param {string} key - Unique asset key of this image file.
  25230. * @param {string} url - URL of image file.
  25231. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  25232. * @return {Phaser.Loader} This Loader instance.
  25233. */
  25234. image: function (key, url, overwrite) {
  25235. if (typeof overwrite === "undefined") { overwrite = false; }
  25236. if (overwrite)
  25237. {
  25238. this.replaceInFileList('image', key, url);
  25239. }
  25240. else
  25241. {
  25242. this.addToFileList('image', key, url);
  25243. }
  25244. return this;
  25245. },
  25246. /**
  25247. * Add a text file to the Loader.
  25248. *
  25249. * @method Phaser.Loader#text
  25250. * @param {string} key - Unique asset key of the text file.
  25251. * @param {string} url - URL of the text file.
  25252. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  25253. * @return {Phaser.Loader} This Loader instance.
  25254. */
  25255. text: function (key, url, overwrite) {
  25256. if (typeof overwrite === "undefined") { overwrite = false; }
  25257. if (overwrite)
  25258. {
  25259. this.replaceInFileList('text', key, url);
  25260. }
  25261. else
  25262. {
  25263. this.addToFileList('text', key, url);
  25264. }
  25265. return this;
  25266. },
  25267. /**
  25268. * Add a JavaScript file to the Loader. Once loaded the JavaScript file will be automatically turned into a script tag (and executed), so be careful what you load!
  25269. *
  25270. * @method Phaser.Loader#script
  25271. * @param {string} key - Unique asset key of the script file.
  25272. * @param {string} url - URL of the JavaScript file.
  25273. * @return {Phaser.Loader} This Loader instance.
  25274. */
  25275. script: function (key, url) {
  25276. this.addToFileList('script', key, url);
  25277. return this;
  25278. },
  25279. /**
  25280. * Add a new sprite sheet to the loader.
  25281. *
  25282. * @method Phaser.Loader#spritesheet
  25283. * @param {string} key - Unique asset key of the sheet file.
  25284. * @param {string} url - URL of the sheet file.
  25285. * @param {number} frameWidth - Width of each single frame.
  25286. * @param {number} frameHeight - Height of each single frame.
  25287. * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames.
  25288. * @return {Phaser.Loader} This Loader instance.
  25289. */
  25290. spritesheet: function (key, url, frameWidth, frameHeight, frameMax) {
  25291. if (typeof frameMax === "undefined") { frameMax = -1; }
  25292. this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax });
  25293. return this;
  25294. },
  25295. /**
  25296. * Add a new tile set to the loader. These are used in the rendering of tile maps.
  25297. *
  25298. * @method Phaser.Loader#tileset
  25299. * @param {string} key - Unique asset key of the tileset file.
  25300. * @param {string} url - URL of the tileset.
  25301. * @param {number} tileWidth - Width of each single tile in pixels.
  25302. * @param {number} tileHeight - Height of each single tile in pixels.
  25303. * @param {number} [tileMax=-1] - How many tiles in this tileset. If not specified it will divide the whole image into tiles.
  25304. * @param {number} [tileMargin=0] - If the tiles have been drawn with a margin, specify the amount here.
  25305. * @param {number} [tileSpacing=0] - If the tiles have been drawn with spacing between them, specify the amount here.
  25306. * @return {Phaser.Loader} This Loader instance.
  25307. */
  25308. tileset: function (key, url, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing) {
  25309. if (typeof tileMax === "undefined") { tileMax = -1; }
  25310. if (typeof tileMargin === "undefined") { tileMargin = 0; }
  25311. if (typeof tileSpacing === "undefined") { tileSpacing = 0; }
  25312. this.addToFileList('tileset', key, url, { tileWidth: tileWidth, tileHeight: tileHeight, tileMax: tileMax, tileMargin: tileMargin, tileSpacing: tileSpacing });
  25313. return this;
  25314. },
  25315. /**
  25316. * Add a new audio file to the loader.
  25317. *
  25318. * @method Phaser.Loader#audio
  25319. * @param {string} key - Unique asset key of the audio file.
  25320. * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'jump.mp3', 'jump.ogg', 'jump.m4a' ] or a single string containing just one URL.
  25321. * @param {boolean} autoDecode - When using Web Audio the audio files can either be decoded at load time or run-time. They can't be played until they are decoded, but this let's you control when that happens. Decoding is a non-blocking async process.
  25322. * @return {Phaser.Loader} This Loader instance.
  25323. */
  25324. audio: function (key, urls, autoDecode) {
  25325. if (typeof autoDecode === "undefined") { autoDecode = true; }
  25326. this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode });
  25327. return this;
  25328. },
  25329. /**
  25330. * Add a new tilemap loading request.
  25331. *
  25332. * @method Phaser.Loader#tilemap
  25333. * @param {string} key - Unique asset key of the tilemap data.
  25334. * @param {string} [mapDataURL] - The url of the map data file (csv/json)
  25335. * @param {object} [mapData] - An optional JSON data object. If given then the mapDataURL is ignored and this JSON object is used for map data instead.
  25336. * @param {string} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON.
  25337. * @return {Phaser.Loader} This Loader instance.
  25338. */
  25339. tilemap: function (key, mapDataURL, mapData, format) {
  25340. if (typeof mapDataURL === "undefined") { mapDataURL = null; }
  25341. if (typeof mapData === "undefined") { mapData = null; }
  25342. if (typeof format === "undefined") { format = Phaser.Tilemap.CSV; }
  25343. if (mapDataURL == null && mapData == null)
  25344. {
  25345. console.warn('Phaser.Loader.tilemap - Both mapDataURL and mapData are null. One must be set.');
  25346. return this;
  25347. }
  25348. // A map data object has been given
  25349. if (mapData)
  25350. {
  25351. switch (format)
  25352. {
  25353. // A csv string or object has been given
  25354. case Phaser.Tilemap.CSV:
  25355. break;
  25356. // An xml string or object has been given
  25357. case Phaser.Tilemap.TILED_JSON:
  25358. if (typeof mapData === 'string')
  25359. {
  25360. mapData = JSON.parse(mapData);
  25361. }
  25362. break;
  25363. }
  25364. this.game.cache.addTilemap(key, null, mapData, format);
  25365. }
  25366. else
  25367. {
  25368. this.addToFileList('tilemap', key, mapDataURL, { format: format });
  25369. }
  25370. return this;
  25371. },
  25372. /**
  25373. * Add a new bitmap font loading request.
  25374. *
  25375. * @method Phaser.Loader#bitmapFont
  25376. * @param {string} key - Unique asset key of the bitmap font.
  25377. * @param {string} textureURL - The url of the font image file.
  25378. * @param {string} [xmlURL] - The url of the font data file (xml/fnt)
  25379. * @param {object} [xmlData] - An optional XML data object.
  25380. * @return {Phaser.Loader} This Loader instance.
  25381. */
  25382. bitmapFont: function (key, textureURL, xmlURL, xmlData) {
  25383. if (typeof xmlURL === "undefined") { xmlURL = null; }
  25384. if (typeof xmlData === "undefined") { xmlData = null; }
  25385. // A URL to a json/xml file has been given
  25386. if (xmlURL)
  25387. {
  25388. this.addToFileList('bitmapfont', key, textureURL, { xmlURL: xmlURL });
  25389. }
  25390. else
  25391. {
  25392. // An xml string or object has been given
  25393. if (typeof xmlData === 'string')
  25394. {
  25395. var xml;
  25396. try {
  25397. if (window['DOMParser'])
  25398. {
  25399. var domparser = new DOMParser();
  25400. xml = domparser.parseFromString(xmlData, "text/xml");
  25401. }
  25402. else
  25403. {
  25404. xml = new ActiveXObject("Microsoft.XMLDOM");
  25405. xml.async = 'false';
  25406. xml.loadXML(xmlData);
  25407. }
  25408. }
  25409. catch (e)
  25410. {
  25411. xml = undefined;
  25412. }
  25413. if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
  25414. {
  25415. throw new Error("Phaser.Loader. Invalid Bitmap Font XML given");
  25416. }
  25417. else
  25418. {
  25419. this.addToFileList('bitmapfont', key, textureURL, { xmlURL: null, xmlData: xml });
  25420. }
  25421. }
  25422. }
  25423. return this;
  25424. },
  25425. /**
  25426. * Add a new texture atlas to the loader. This atlas uses the JSON Array data format.
  25427. *
  25428. * @method Phaser.Loader#atlasJSONArray
  25429. * @param {string} key - Unique asset key of the texture atlas file.
  25430. * @param {string} textureURL - The url of the texture atlas image file.
  25431. * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
  25432. * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
  25433. * @return {Phaser.Loader} This Loader instance.
  25434. */
  25435. atlasJSONArray: function (key, textureURL, atlasURL, atlasData) {
  25436. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
  25437. },
  25438. /**
  25439. * Add a new texture atlas to the loader. This atlas uses the JSON Hash data format.
  25440. *
  25441. * @method Phaser.Loader#atlasJSONHash
  25442. * @param {string} key - Unique asset key of the texture atlas file.
  25443. * @param {string} textureURL - The url of the texture atlas image file.
  25444. * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
  25445. * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
  25446. * @return {Phaser.Loader} This Loader instance.
  25447. */
  25448. atlasJSONHash: function (key, textureURL, atlasURL, atlasData) {
  25449. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH);
  25450. },
  25451. /**
  25452. * Add a new texture atlas to the loader. This atlas uses the Starling XML data format.
  25453. *
  25454. * @method Phaser.Loader#atlasXML
  25455. * @param {string} key - Unique asset key of the texture atlas file.
  25456. * @param {string} textureURL - The url of the texture atlas image file.
  25457. * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
  25458. * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
  25459. * @return {Phaser.Loader} This Loader instance.
  25460. */
  25461. atlasXML: function (key, textureURL, atlasURL, atlasData) {
  25462. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING);
  25463. },
  25464. /**
  25465. * Add a new texture atlas to the loader.
  25466. *
  25467. * @method Phaser.Loader#atlas
  25468. * @param {string} key - Unique asset key of the texture atlas file.
  25469. * @param {string} textureURL - The url of the texture atlas image file.
  25470. * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
  25471. * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
  25472. * @param {number} [format] - A value describing the format of the data, the default is Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY.
  25473. * @return {Phaser.Loader} This Loader instance.
  25474. */
  25475. atlas: function (key, textureURL, atlasURL, atlasData, format) {
  25476. if (typeof atlasURL === "undefined") { atlasURL = null; }
  25477. if (typeof atlasData === "undefined") { atlasData = null; }
  25478. if (typeof format === "undefined") { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; }
  25479. // A URL to a json/xml file has been given
  25480. if (atlasURL)
  25481. {
  25482. this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format });
  25483. }
  25484. else
  25485. {
  25486. switch (format)
  25487. {
  25488. // A json string or object has been given
  25489. case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY:
  25490. if (typeof atlasData === 'string')
  25491. {
  25492. atlasData = JSON.parse(atlasData);
  25493. }
  25494. break;
  25495. // An xml string or object has been given
  25496. case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING:
  25497. if (typeof atlasData === 'string')
  25498. {
  25499. var xml;
  25500. try {
  25501. if (window['DOMParser'])
  25502. {
  25503. var domparser = new DOMParser();
  25504. xml = domparser.parseFromString(atlasData, "text/xml");
  25505. }
  25506. else
  25507. {
  25508. xml = new ActiveXObject("Microsoft.XMLDOM");
  25509. xml.async = 'false';
  25510. xml.loadXML(atlasData);
  25511. }
  25512. }
  25513. catch (e)
  25514. {
  25515. xml = undefined;
  25516. }
  25517. if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
  25518. {
  25519. throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");
  25520. }
  25521. else
  25522. {
  25523. atlasData = xml;
  25524. }
  25525. }
  25526. break;
  25527. }
  25528. this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format });
  25529. }
  25530. return this;
  25531. },
  25532. /**
  25533. * Remove loading request of a file.
  25534. *
  25535. * @method Phaser.Loader#removeFile
  25536. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  25537. * @param {string} key - Key of the file you want to remove.
  25538. */
  25539. removeFile: function (type, key) {
  25540. var file = this.getAsset(type, key);
  25541. if (file !== false)
  25542. {
  25543. this._fileList.splice(file.index, 1);
  25544. }
  25545. },
  25546. /**
  25547. * Remove all file loading requests.
  25548. *
  25549. * @method Phaser.Loader#removeAll
  25550. */
  25551. removeAll: function () {
  25552. this._fileList.length = 0;
  25553. },
  25554. /**
  25555. * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so.
  25556. *
  25557. * @method Phaser.Loader#start
  25558. */
  25559. start: function () {
  25560. if (this.isLoading)
  25561. {
  25562. return;
  25563. }
  25564. this.progress = 0;
  25565. this.hasLoaded = false;
  25566. this.isLoading = true;
  25567. this.onLoadStart.dispatch(this._fileList.length);
  25568. if (this._fileList.length > 0)
  25569. {
  25570. this._fileIndex = 0;
  25571. this._progressChunk = 100 / this._fileList.length;
  25572. this.loadFile();
  25573. }
  25574. else
  25575. {
  25576. this.progress = 100;
  25577. this.hasLoaded = true;
  25578. this.onLoadComplete.dispatch();
  25579. }
  25580. },
  25581. /**
  25582. * Load files. Private method ONLY used by loader.
  25583. *
  25584. * @method Phaser.Loader#loadFile
  25585. * @private
  25586. */
  25587. loadFile: function () {
  25588. if (!this._fileList[this._fileIndex])
  25589. {
  25590. console.warn('Phaser.Loader loadFile invalid index ' + this._fileIndex);
  25591. return;
  25592. }
  25593. var file = this._fileList[this._fileIndex];
  25594. var _this = this;
  25595. // Image or Data?
  25596. switch (file.type)
  25597. {
  25598. case 'image':
  25599. case 'spritesheet':
  25600. case 'textureatlas':
  25601. case 'bitmapfont':
  25602. case 'tileset':
  25603. file.data = new Image();
  25604. file.data.name = file.key;
  25605. file.data.onload = function () {
  25606. return _this.fileComplete(_this._fileIndex);
  25607. };
  25608. file.data.onerror = function () {
  25609. return _this.fileError(_this._fileIndex);
  25610. };
  25611. file.data.crossOrigin = this.crossOrigin;
  25612. file.data.src = this.baseURL + file.url;
  25613. break;
  25614. case 'audio':
  25615. file.url = this.getAudioURL(file.url);
  25616. if (file.url !== null)
  25617. {
  25618. // WebAudio or Audio Tag?
  25619. if (this.game.sound.usingWebAudio)
  25620. {
  25621. this._xhr.open("GET", this.baseURL + file.url, true);
  25622. this._xhr.responseType = "arraybuffer";
  25623. this._xhr.onload = function () {
  25624. return _this.fileComplete(_this._fileIndex);
  25625. };
  25626. this._xhr.onerror = function () {
  25627. return _this.fileError(_this._fileIndex);
  25628. };
  25629. this._xhr.send();
  25630. }
  25631. else if (this.game.sound.usingAudioTag)
  25632. {
  25633. if (this.game.sound.touchLocked)
  25634. {
  25635. // If audio is locked we can't do this yet, so need to queue this load request. Bum.
  25636. file.data = new Audio();
  25637. file.data.name = file.key;
  25638. file.data.preload = 'auto';
  25639. file.data.src = this.baseURL + file.url;
  25640. this.fileComplete(this._fileIndex);
  25641. }
  25642. else
  25643. {
  25644. file.data = new Audio();
  25645. file.data.name = file.key;
  25646. file.data.onerror = function () {
  25647. return _this.fileError(_this._fileIndex);
  25648. };
  25649. file.data.preload = 'auto';
  25650. file.data.src = this.baseURL + file.url;
  25651. file.data.addEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete(this._fileIndex), false);
  25652. file.data.load();
  25653. }
  25654. }
  25655. }
  25656. else
  25657. {
  25658. this.fileError(this._fileIndex);
  25659. }
  25660. break;
  25661. case 'tilemap':
  25662. this._xhr.open("GET", this.baseURL + file.url, true);
  25663. this._xhr.responseType = "text";
  25664. if (file.format === Phaser.Tilemap.TILED_JSON)
  25665. {
  25666. this._xhr.onload = function () {
  25667. return _this.jsonLoadComplete(_this._fileIndex);
  25668. };
  25669. }
  25670. else if (file.format === Phaser.Tilemap.CSV)
  25671. {
  25672. this._xhr.onload = function () {
  25673. return _this.csvLoadComplete(_this._fileIndex);
  25674. };
  25675. }
  25676. else
  25677. {
  25678. throw new Error("Phaser.Loader. Invalid Tilemap format: " + file.format);
  25679. }
  25680. this._xhr.onerror = function () {
  25681. return _this.dataLoadError(_this._fileIndex);
  25682. };
  25683. this._xhr.send();
  25684. break;
  25685. case 'text':
  25686. this._xhr.open("GET", this.baseURL + file.url, true);
  25687. this._xhr.responseType = "text";
  25688. this._xhr.onload = function () {
  25689. return _this.fileComplete(_this._fileIndex);
  25690. };
  25691. this._xhr.onerror = function () {
  25692. return _this.fileError(_this._fileIndex);
  25693. };
  25694. this._xhr.send();
  25695. break;
  25696. case 'script':
  25697. this._xhr.open("GET", this.baseURL + file.url, true);
  25698. this._xhr.responseType = "text";
  25699. this._xhr.onload = function () {
  25700. return _this.fileComplete(_this._fileIndex);
  25701. };
  25702. this._xhr.onerror = function () {
  25703. return _this.fileError(_this._fileIndex);
  25704. };
  25705. this._xhr.send();
  25706. break;
  25707. }
  25708. },
  25709. /**
  25710. * Private method ONLY used by loader.
  25711. * @method Phaser.Loader#getAudioURL
  25712. * @param {array|string} urls - Either an array of audio file URLs or a string containing a single URL path.
  25713. * @private
  25714. */
  25715. getAudioURL: function (urls) {
  25716. var extension;
  25717. if (typeof urls === 'string') { urls = [urls]; }
  25718. for (var i = 0; i < urls.length; i++)
  25719. {
  25720. extension = urls[i].toLowerCase();
  25721. extension = extension.substr((Math.max(0, extension.lastIndexOf(".")) || Infinity) + 1);
  25722. if (this.game.device.canPlayAudio(extension))
  25723. {
  25724. return urls[i];
  25725. }
  25726. }
  25727. return null;
  25728. },
  25729. /**
  25730. * Error occured when loading a file.
  25731. *
  25732. * @method Phaser.Loader#fileError
  25733. * @param {number} index - The index of the file in the file queue that errored.
  25734. */
  25735. fileError: function (index) {
  25736. this._fileList[index].loaded = true;
  25737. this._fileList[index].error = true;
  25738. this.onFileError.dispatch(this._fileList[index].key, this._fileList[index]);
  25739. console.warn("Phaser.Loader error loading file: " + this._fileList[index].key + ' from URL ' + this._fileList[index].url);
  25740. this.nextFile(index, false);
  25741. },
  25742. /**
  25743. * Called when a file is successfully loaded.
  25744. *
  25745. * @method Phaser.Loader#fileComplete
  25746. * @param {number} index - The index of the file in the file queue that loaded.
  25747. */
  25748. fileComplete: function (index) {
  25749. if (!this._fileList[index])
  25750. {
  25751. console.warn('Phaser.Loader fileComplete invalid index ' + index);
  25752. return;
  25753. }
  25754. var file = this._fileList[index];
  25755. file.loaded = true;
  25756. var loadNext = true;
  25757. var _this = this;
  25758. switch (file.type)
  25759. {
  25760. case 'image':
  25761. this.game.cache.addImage(file.key, file.url, file.data);
  25762. break;
  25763. case 'spritesheet':
  25764. this.game.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax);
  25765. break;
  25766. case 'tileset':
  25767. this.game.cache.addTileset(file.key, file.url, file.data, file.tileWidth, file.tileHeight, file.tileMax, file.tileMargin, file.tileSpacing);
  25768. break;
  25769. case 'textureatlas':
  25770. if (file.atlasURL == null)
  25771. {
  25772. this.game.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format);
  25773. }
  25774. else
  25775. {
  25776. // Load the JSON or XML before carrying on with the next file
  25777. loadNext = false;
  25778. this._xhr.open("GET", this.baseURL + file.atlasURL, true);
  25779. this._xhr.responseType = "text";
  25780. if (file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH)
  25781. {
  25782. this._xhr.onload = function () {
  25783. return _this.jsonLoadComplete(index);
  25784. };
  25785. }
  25786. else if (file.format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
  25787. {
  25788. this._xhr.onload = function () {
  25789. return _this.xmlLoadComplete(index);
  25790. };
  25791. }
  25792. else
  25793. {
  25794. throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format);
  25795. }
  25796. this._xhr.onerror = function () {
  25797. return _this.dataLoadError(index);
  25798. };
  25799. this._xhr.send();
  25800. }
  25801. break;
  25802. case 'bitmapfont':
  25803. if (file.xmlURL == null)
  25804. {
  25805. this.game.cache.addBitmapFont(file.key, file.url, file.data, file.xmlData);
  25806. }
  25807. else
  25808. {
  25809. // Load the XML before carrying on with the next file
  25810. loadNext = false;
  25811. this._xhr.open("GET", this.baseURL + file.xmlURL, true);
  25812. this._xhr.responseType = "text";
  25813. this._xhr.onload = function () {
  25814. return _this.xmlLoadComplete(index);
  25815. };
  25816. this._xhr.onerror = function () {
  25817. return _this.dataLoadError(index);
  25818. };
  25819. this._xhr.send();
  25820. }
  25821. break;
  25822. case 'audio':
  25823. if (this.game.sound.usingWebAudio)
  25824. {
  25825. file.data = this._xhr.response;
  25826. this.game.cache.addSound(file.key, file.url, file.data, true, false);
  25827. if (file.autoDecode)
  25828. {
  25829. this.game.cache.updateSound(key, 'isDecoding', true);
  25830. var that = this;
  25831. var key = file.key;
  25832. this.game.sound.context.decodeAudioData(file.data, function (buffer) {
  25833. if (buffer)
  25834. {
  25835. that.game.cache.decodedSound(key, buffer);
  25836. }
  25837. });
  25838. }
  25839. }
  25840. else
  25841. {
  25842. file.data.removeEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete);
  25843. this.game.cache.addSound(file.key, file.url, file.data, false, true);
  25844. }
  25845. break;
  25846. case 'text':
  25847. file.data = this._xhr.responseText;
  25848. this.game.cache.addText(file.key, file.url, file.data);
  25849. break;
  25850. case 'script':
  25851. file.data = document.createElement('script');
  25852. file.data.language = 'javascript';
  25853. file.data.type = 'text/javascript';
  25854. file.data.defer = false;
  25855. file.data.text = this._xhr.responseText;
  25856. document.head.appendChild(file.data);
  25857. break;
  25858. }
  25859. if (loadNext)
  25860. {
  25861. this.nextFile(index, true);
  25862. }
  25863. },
  25864. /**
  25865. * Successfully loaded a JSON file.
  25866. *
  25867. * @method Phaser.Loader#jsonLoadComplete
  25868. * @param {number} index - The index of the file in the file queue that loaded.
  25869. */
  25870. jsonLoadComplete: function (index) {
  25871. if (!this._fileList[index])
  25872. {
  25873. console.warn('Phaser.Loader jsonLoadComplete invalid index ' + index);
  25874. return;
  25875. }
  25876. var file = this._fileList[index];
  25877. var data = JSON.parse(this._xhr.responseText);
  25878. file.loaded = true;
  25879. if (file.type === 'tilemap')
  25880. {
  25881. this.game.cache.addTilemap(file.key, file.url, data, file.format);
  25882. }
  25883. else
  25884. {
  25885. this.game.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format);
  25886. }
  25887. this.nextFile(index, true);
  25888. },
  25889. /**
  25890. * Successfully loaded a CSV file.
  25891. *
  25892. * @method Phaser.Loader#csvLoadComplete
  25893. * @param {number} index - The index of the file in the file queue that loaded.
  25894. */
  25895. csvLoadComplete: function (index) {
  25896. if (!this._fileList[index])
  25897. {
  25898. console.warn('Phaser.Loader csvLoadComplete invalid index ' + index);
  25899. return;
  25900. }
  25901. var file = this._fileList[index];
  25902. var data = this._xhr.responseText;
  25903. file.loaded = true;
  25904. this.game.cache.addTilemap(file.key, file.url, data, file.format);
  25905. this.nextFile(index, true);
  25906. },
  25907. /**
  25908. * Error occured when load a JSON.
  25909. *
  25910. * @method Phaser.Loader#dataLoadError
  25911. * @param {number} index - The index of the file in the file queue that errored.
  25912. */
  25913. dataLoadError: function (index) {
  25914. var file = this._fileList[index];
  25915. file.loaded = true;
  25916. file.error = true;
  25917. console.warn("Phaser.Loader dataLoadError: " + file.key);
  25918. this.nextFile(index, true);
  25919. },
  25920. /**
  25921. * Successfully loaded an XML file.
  25922. *
  25923. * @method Phaser.Loader#xmlLoadComplete
  25924. * @param {number} index - The index of the file in the file queue that loaded.
  25925. */
  25926. xmlLoadComplete: function (index) {
  25927. var data = this._xhr.responseText;
  25928. var xml;
  25929. try
  25930. {
  25931. if (window['DOMParser'])
  25932. {
  25933. var domparser = new DOMParser();
  25934. xml = domparser.parseFromString(data, "text/xml");
  25935. }
  25936. else
  25937. {
  25938. xml = new ActiveXObject("Microsoft.XMLDOM");
  25939. xml.async = 'false';
  25940. xml.loadXML(data);
  25941. }
  25942. }
  25943. catch (e)
  25944. {
  25945. xml = undefined;
  25946. }
  25947. if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
  25948. {
  25949. throw new Error("Phaser.Loader. Invalid XML given");
  25950. }
  25951. var file = this._fileList[index];
  25952. file.loaded = true;
  25953. if (file.type == 'bitmapfont')
  25954. {
  25955. this.game.cache.addBitmapFont(file.key, file.url, file.data, xml);
  25956. }
  25957. else if (file.type == 'textureatlas')
  25958. {
  25959. this.game.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format);
  25960. }
  25961. this.nextFile(index, true);
  25962. },
  25963. /**
  25964. * Handle loading next file.
  25965. *
  25966. * @param {number} previousIndex - Index of the previously loaded asset.
  25967. * @param {boolean} success - Whether the previous asset loaded successfully or not.
  25968. * @private
  25969. */
  25970. nextFile: function (previousIndex, success) {
  25971. this.progress = Math.round(this.progress + this._progressChunk);
  25972. if (this.progress > 100)
  25973. {
  25974. this.progress = 100;
  25975. }
  25976. if (this.preloadSprite !== null)
  25977. {
  25978. if (this.preloadSprite.direction === 0)
  25979. {
  25980. this.preloadSprite.crop.width = Math.floor((this.preloadSprite.width / 100) * this.progress);
  25981. }
  25982. else
  25983. {
  25984. this.preloadSprite.crop.height = Math.floor((this.preloadSprite.height / 100) * this.progress);
  25985. }
  25986. this.preloadSprite.sprite.crop = this.preloadSprite.crop;
  25987. }
  25988. this.onFileComplete.dispatch(this.progress, this._fileList[previousIndex].key, success, this.totalLoadedFiles(), this._fileList.length);
  25989. if (this.totalQueuedFiles() > 0)
  25990. {
  25991. this._fileIndex++;
  25992. this.loadFile();
  25993. }
  25994. else
  25995. {
  25996. this.hasLoaded = true;
  25997. this.isLoading = false;
  25998. this.removeAll();
  25999. this.onLoadComplete.dispatch();
  26000. }
  26001. },
  26002. /**
  26003. * Returns the number of files that have already been loaded, even if they errored.
  26004. *
  26005. * @return {number} The number of files that have already been loaded (even if they errored)
  26006. */
  26007. totalLoadedFiles: function () {
  26008. var total = 0;
  26009. for (var i = 0; i < this._fileList.length; i++)
  26010. {
  26011. if (this._fileList[i].loaded)
  26012. {
  26013. total++;
  26014. }
  26015. }
  26016. return total;
  26017. },
  26018. /**
  26019. * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file is in the queue is loaded.
  26020. *
  26021. * @return {number} The number of files that still remain in the load queue.
  26022. */
  26023. totalQueuedFiles: function () {
  26024. var total = 0;
  26025. for (var i = 0; i < this._fileList.length; i++)
  26026. {
  26027. if (this._fileList[i].loaded === false)
  26028. {
  26029. total++;
  26030. }
  26031. }
  26032. return total;
  26033. }
  26034. };
  26035. /**
  26036. * @author Richard Davey <rich@photonstorm.com>
  26037. * @copyright 2013 Photon Storm Ltd.
  26038. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  26039. */
  26040. /**
  26041. * Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache.
  26042. *
  26043. * @class Phaser.LoaderParser
  26044. */
  26045. Phaser.LoaderParser = {
  26046. /**
  26047. * Parse frame data from an XML file.
  26048. * @method Phaser.LoaderParser.bitmapFont
  26049. * @param {object} xml - XML data you want to parse.
  26050. * @return {FrameData} Generated FrameData object.
  26051. */
  26052. bitmapFont: function (game, xml, cacheKey) {
  26053. // Malformed?
  26054. if (!xml.getElementsByTagName('font'))
  26055. {
  26056. console.warn("Phaser.LoaderParser.bitmapFont: Invalid XML given, missing <font> tag");
  26057. return;
  26058. }
  26059. var texture = PIXI.TextureCache[cacheKey];
  26060. var data = {};
  26061. var info = xml.getElementsByTagName("info")[0];
  26062. var common = xml.getElementsByTagName("common")[0];
  26063. data.font = info.attributes.getNamedItem("face").nodeValue;
  26064. data.size = parseInt(info.attributes.getNamedItem("size").nodeValue, 10);
  26065. data.lineHeight = parseInt(common.attributes.getNamedItem("lineHeight").nodeValue, 10);
  26066. data.chars = {};
  26067. //parse letters
  26068. var letters = xml.getElementsByTagName("char");
  26069. for (var i = 0; i < letters.length; i++)
  26070. {
  26071. var charCode = parseInt(letters[i].attributes.getNamedItem("id").nodeValue, 10);
  26072. var textureRect = {
  26073. x: parseInt(letters[i].attributes.getNamedItem("x").nodeValue, 10),
  26074. y: parseInt(letters[i].attributes.getNamedItem("y").nodeValue, 10),
  26075. width: parseInt(letters[i].attributes.getNamedItem("width").nodeValue, 10),
  26076. height: parseInt(letters[i].attributes.getNamedItem("height").nodeValue, 10)
  26077. };
  26078. // Note: This means you can only have 1 BitmapFont loaded at once!
  26079. // Need to replace this with our own handler soon.
  26080. PIXI.TextureCache[charCode] = new PIXI.Texture(texture, textureRect);
  26081. data.chars[charCode] = {
  26082. xOffset: parseInt(letters[i].attributes.getNamedItem("xoffset").nodeValue, 10),
  26083. yOffset: parseInt(letters[i].attributes.getNamedItem("yoffset").nodeValue, 10),
  26084. xAdvance: parseInt(letters[i].attributes.getNamedItem("xadvance").nodeValue, 10),
  26085. kerning: {},
  26086. texture:new PIXI.Texture(texture, textureRect)
  26087. };
  26088. }
  26089. //parse kernings
  26090. var kernings = xml.getElementsByTagName("kerning");
  26091. for (i = 0; i < kernings.length; i++)
  26092. {
  26093. var first = parseInt(kernings[i].attributes.getNamedItem("first").nodeValue, 10);
  26094. var second = parseInt(kernings[i].attributes.getNamedItem("second").nodeValue, 10);
  26095. var amount = parseInt(kernings[i].attributes.getNamedItem("amount").nodeValue, 10);
  26096. data.chars[second].kerning[first] = amount;
  26097. }
  26098. PIXI.BitmapText.fonts[data.font] = data;
  26099. }
  26100. };
  26101. /**
  26102. * @author Richard Davey <rich@photonstorm.com>
  26103. * @copyright 2013 Photon Storm Ltd.
  26104. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  26105. */
  26106. /**
  26107. * The Sound class constructor.
  26108. *
  26109. * @class Phaser.Sound
  26110. * @classdesc The Sound class
  26111. * @constructor
  26112. * @param {Phaser.Game} game - Reference to the current game instance.
  26113. * @param {string} key - Asset key for the sound.
  26114. * @param {number} [volume=1] - Default value for the volume, between 0 and 1.
  26115. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  26116. */
  26117. Phaser.Sound = function (game, key, volume, loop, connect) {
  26118. if (typeof volume == 'undefined') { volume = 1; }
  26119. if (typeof loop == 'undefined') { loop = false; }
  26120. if (typeof connect === 'undefined') { connect = game.sound.connectToMaster; }
  26121. /**
  26122. * A reference to the currently running Game.
  26123. * @property {Phaser.Game} game
  26124. */
  26125. this.game = game;
  26126. /**
  26127. * @property {string} name - Name of the sound.
  26128. */
  26129. this.name = key;
  26130. /**
  26131. * @property {string} key - Asset key for the sound.
  26132. */
  26133. this.key = key;
  26134. /**
  26135. * @property {boolean} loop - Whether or not the sound will loop.
  26136. */
  26137. this.loop = loop;
  26138. /**
  26139. * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
  26140. * @private
  26141. */
  26142. this._volume = volume;
  26143. /**
  26144. * @property {object} markers - The sound markers.
  26145. */
  26146. this.markers = {};
  26147. /**
  26148. * @property {AudioContext} context - Reference to the AudioContext instance.
  26149. */
  26150. this.context = null;
  26151. /**
  26152. * @property {Description} _buffer - Decoded data buffer / Audio tag.
  26153. * @private
  26154. */
  26155. this._buffer = null;
  26156. /**
  26157. * @property {boolean} _muted - Boolean indicating whether the sound is muted or not.
  26158. * @private
  26159. * @default
  26160. */
  26161. this._muted = false;
  26162. /**
  26163. * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically.
  26164. */
  26165. this.autoplay = false;
  26166. /**
  26167. * @property {number} totalDuration - The total duration of the sound, in milliseconds
  26168. */
  26169. this.totalDuration = 0;
  26170. /**
  26171. * @property {number} startTime - The time the Sound starts at (typically 0 unless starting from a marker)
  26172. * @default
  26173. */
  26174. this.startTime = 0;
  26175. /**
  26176. * @property {number} currentTime - The current time the sound is at.
  26177. */
  26178. this.currentTime = 0;
  26179. /**
  26180. * @property {number} duration - The duration of the sound.
  26181. */
  26182. this.duration = 0;
  26183. /**
  26184. * @property {number} stopTime - The time the sound stopped.
  26185. */
  26186. this.stopTime = 0;
  26187. /**
  26188. * @property {boolean} paused - true if the sound is paused, otherwise false.
  26189. * @default
  26190. */
  26191. this.paused = false;
  26192. /**
  26193. * @property {number} pausedPosition - The position the sound had reached when it was paused.
  26194. */
  26195. this.pausedPosition = 0;
  26196. /**
  26197. * @property {number} pausedTime - The game time at which the sound was paused.
  26198. */
  26199. this.pausedTime = 0;
  26200. /**
  26201. * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false.
  26202. * @default
  26203. */
  26204. this.isPlaying = false;
  26205. /**
  26206. * @property {string} currentMarker - The string ID of the currently playing marker, if any.
  26207. * @default
  26208. */
  26209. this.currentMarker = '';
  26210. /**
  26211. * @property {boolean} pendingPlayback - true if the sound file is pending playback
  26212. * @readonly
  26213. */
  26214. this.pendingPlayback = false;
  26215. /**
  26216. * @property {boolean} override - if true when you play this sound it will always start from the beginning.
  26217. * @default
  26218. */
  26219. this.override = false;
  26220. /**
  26221. * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio.
  26222. * @readonly
  26223. */
  26224. this.usingWebAudio = this.game.sound.usingWebAudio;
  26225. /**
  26226. * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag.
  26227. */
  26228. this.usingAudioTag = this.game.sound.usingAudioTag;
  26229. /**
  26230. * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode.input.
  26231. */
  26232. this.externalNode = null;
  26233. if (this.usingWebAudio)
  26234. {
  26235. this.context = this.game.sound.context;
  26236. this.masterGainNode = this.game.sound.masterGain;
  26237. if (typeof this.context.createGain === 'undefined')
  26238. {
  26239. this.gainNode = this.context.createGainNode();
  26240. }
  26241. else
  26242. {
  26243. this.gainNode = this.context.createGain();
  26244. }
  26245. this.gainNode.gain.value = volume * this.game.sound.volume;
  26246. if (connect)
  26247. {
  26248. this.gainNode.connect(this.masterGainNode);
  26249. }
  26250. }
  26251. else
  26252. {
  26253. if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key))
  26254. {
  26255. this._sound = this.game.cache.getSoundData(key);
  26256. this.totalDuration = 0;
  26257. if (this._sound.duration)
  26258. {
  26259. this.totalDuration = this._sound.duration;
  26260. }
  26261. }
  26262. else
  26263. {
  26264. this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this);
  26265. }
  26266. }
  26267. /**
  26268. * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files)
  26269. */
  26270. this.onDecoded = new Phaser.Signal();
  26271. /**
  26272. * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played.
  26273. */
  26274. this.onPlay = new Phaser.Signal();
  26275. /**
  26276. * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused.
  26277. */
  26278. this.onPause = new Phaser.Signal();
  26279. /**
  26280. * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state.
  26281. */
  26282. this.onResume = new Phaser.Signal();
  26283. /**
  26284. * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback.
  26285. */
  26286. this.onLoop = new Phaser.Signal();
  26287. /**
  26288. * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback.
  26289. */
  26290. this.onStop = new Phaser.Signal();
  26291. /**
  26292. * @property {Phaser.Signal} onMute - The onMouse event is dispatched when this sound is muted.
  26293. */
  26294. this.onMute = new Phaser.Signal();
  26295. /**
  26296. * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback.
  26297. */
  26298. this.onMarkerComplete = new Phaser.Signal();
  26299. };
  26300. Phaser.Sound.prototype = {
  26301. /**
  26302. * Called automatically when this sound is unlocked.
  26303. * @method Phaser.Sound#soundHasUnlocked
  26304. * @param {string} key - The Phaser.Cache key of the sound file to check for decoding.
  26305. * @protected
  26306. */
  26307. soundHasUnlocked: function (key) {
  26308. if (key == this.key)
  26309. {
  26310. this._sound = this.game.cache.getSoundData(this.key);
  26311. this.totalDuration = this._sound.duration;
  26312. // console.log('sound has unlocked' + this._sound);
  26313. }
  26314. },
  26315. /**
  26316. * Description.
  26317. * @method Phaser.Sound#addMarker
  26318. * @param {string} name - Description.
  26319. * @param {Description} start - Description.
  26320. * @param {Description} stop - Description.
  26321. * @param {Description} volume - Description.
  26322. * @param {Description} loop - Description.
  26323. addMarker: function (name, start, stop, volume, loop) {
  26324. volume = volume || 1;
  26325. if (typeof loop == 'undefined') { loop = false; }
  26326. this.markers[name] = {
  26327. name: name,
  26328. start: start,
  26329. stop: stop,
  26330. volume: volume,
  26331. duration: stop - start,
  26332. loop: loop
  26333. };
  26334. },
  26335. */
  26336. /**
  26337. * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration.
  26338. * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback.
  26339. *
  26340. * @method Phaser.Sound#addMarker
  26341. * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc.
  26342. * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
  26343. * @param {number} duration - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
  26344. * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume).
  26345. * @param {boolean} [loop=false] - Sets if the sound will loop or not.
  26346. */
  26347. addMarker: function (name, start, duration, volume, loop) {
  26348. volume = volume || 1;
  26349. if (typeof loop == 'undefined') { loop = false; }
  26350. this.markers[name] = {
  26351. name: name,
  26352. start: start,
  26353. stop: start + duration,
  26354. volume: volume,
  26355. duration: duration,
  26356. durationMS: duration * 1000,
  26357. loop: loop
  26358. };
  26359. },
  26360. /**
  26361. * Removes a marker from the sound.
  26362. * @method Phaser.Sound#removeMarker
  26363. * @param {string} name - The key of the marker to remove.
  26364. */
  26365. removeMarker: function (name) {
  26366. delete this.markers[name];
  26367. },
  26368. /**
  26369. * Called automatically by Phaser.SoundManager.
  26370. * @method Phaser.Sound#update
  26371. * @protected
  26372. */
  26373. update: function () {
  26374. if (this.pendingPlayback && this.game.cache.isSoundReady(this.key))
  26375. {
  26376. this.pendingPlayback = false;
  26377. this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop);
  26378. }
  26379. if (this.isPlaying)
  26380. {
  26381. this.currentTime = this.game.time.now - this.startTime;
  26382. if (this.currentTime >= this.durationMS)
  26383. {
  26384. //console.log(this.currentMarker, 'has hit duration');
  26385. if (this.usingWebAudio)
  26386. {
  26387. if (this.loop)
  26388. {
  26389. //console.log('loop1');
  26390. // won't work with markers, needs to reset the position
  26391. this.onLoop.dispatch(this);
  26392. if (this.currentMarker === '')
  26393. {
  26394. //console.log('loop2');
  26395. this.currentTime = 0;
  26396. this.startTime = this.game.time.now;
  26397. }
  26398. else
  26399. {
  26400. //console.log('loop3');
  26401. this.play(this.currentMarker, 0, this.volume, true, true);
  26402. }
  26403. }
  26404. else
  26405. {
  26406. //console.log('stopping, no loop for marker');
  26407. this.stop();
  26408. }
  26409. }
  26410. else
  26411. {
  26412. if (this.loop)
  26413. {
  26414. this.onLoop.dispatch(this);
  26415. this.play(this.currentMarker, 0, this.volume, true, true);
  26416. }
  26417. else
  26418. {
  26419. this.stop();
  26420. }
  26421. }
  26422. }
  26423. }
  26424. },
  26425. /**
  26426. * Play this sound, or a marked section of it.
  26427. * @method Phaser.Sound#play
  26428. * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
  26429. * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
  26430. * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified).
  26431. * @param {boolean} [loop=false] - Loop when it finished playing?
  26432. * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning.
  26433. * @return {Phaser.Sound} This sound instance.
  26434. */
  26435. play: function (marker, position, volume, loop, forceRestart) {
  26436. marker = marker || '';
  26437. position = position || 0;
  26438. if (typeof volume === 'undefined') { volume = this._volume; }
  26439. if (typeof loop === 'undefined') { loop = false; }
  26440. if (typeof forceRestart === 'undefined') { forceRestart = true; }
  26441. // console.log(this.name + ' play ' + marker + ' position ' + position + ' volume ' + volume + ' loop ' + loop, 'force', forceRestart);
  26442. if (this.isPlaying === true && forceRestart === false && this.override === false)
  26443. {
  26444. // Use Restart instead
  26445. return;
  26446. }
  26447. if (this.isPlaying && this.override)
  26448. {
  26449. // console.log('asked to play ' + marker + ' but already playing ' + this.currentMarker);
  26450. if (this.usingWebAudio)
  26451. {
  26452. if (typeof this._sound.stop === 'undefined')
  26453. {
  26454. this._sound.noteOff(0);
  26455. }
  26456. else
  26457. {
  26458. this._sound.stop(0);
  26459. }
  26460. }
  26461. else if (this.usingAudioTag)
  26462. {
  26463. this._sound.pause();
  26464. this._sound.currentTime = 0;
  26465. }
  26466. }
  26467. this.currentMarker = marker;
  26468. if (marker !== '')
  26469. {
  26470. if (this.markers[marker])
  26471. {
  26472. this.position = this.markers[marker].start;
  26473. this.volume = this.markers[marker].volume;
  26474. this.loop = this.markers[marker].loop;
  26475. this.duration = this.markers[marker].duration;
  26476. this.durationMS = this.markers[marker].durationMS;
  26477. // console.log('Marker Loaded: ', marker, 'start:', this.position, 'end: ', this.duration, 'loop', this.loop);
  26478. this._tempMarker = marker;
  26479. this._tempPosition = this.position;
  26480. this._tempVolume = this.volume;
  26481. this._tempLoop = this.loop;
  26482. }
  26483. else
  26484. {
  26485. console.warn("Phaser.Sound.play: audio marker " + marker + " doesn't exist");
  26486. return;
  26487. }
  26488. }
  26489. else
  26490. {
  26491. // console.log('no marker info loaded', marker);
  26492. this.position = position;
  26493. this.volume = volume;
  26494. this.loop = loop;
  26495. this.duration = 0;
  26496. this.durationMS = 0;
  26497. this._tempMarker = marker;
  26498. this._tempPosition = position;
  26499. this._tempVolume = volume;
  26500. this._tempLoop = loop;
  26501. }
  26502. if (this.usingWebAudio)
  26503. {
  26504. // Does the sound need decoding?
  26505. if (this.game.cache.isSoundDecoded(this.key))
  26506. {
  26507. // Do we need to do this every time we play? How about just if the buffer is empty?
  26508. if (this._buffer == null)
  26509. {
  26510. this._buffer = this.game.cache.getSoundData(this.key);
  26511. }
  26512. this._sound = this.context.createBufferSource();
  26513. this._sound.buffer = this._buffer;
  26514. if (this.externalNode)
  26515. {
  26516. this._sound.connect(this.externalNode.input);
  26517. }
  26518. else
  26519. {
  26520. this._sound.connect(this.gainNode);
  26521. }
  26522. this.totalDuration = this._sound.buffer.duration;
  26523. if (this.duration === 0)
  26524. {
  26525. // console.log('duration reset');
  26526. this.duration = this.totalDuration;
  26527. this.durationMS = this.totalDuration * 1000;
  26528. }
  26529. if (this.loop && marker === '')
  26530. {
  26531. this._sound.loop = true;
  26532. }
  26533. // Useful to cache this somewhere perhaps?
  26534. if (typeof this._sound.start === 'undefined')
  26535. {
  26536. this._sound.noteGrainOn(0, this.position, this.duration);
  26537. // this._sound.noteGrainOn(0, this.position, this.duration / 1000);
  26538. //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it
  26539. }
  26540. else
  26541. {
  26542. // this._sound.start(0, this.position, this.duration / 1000);
  26543. this._sound.start(0, this.position, this.duration);
  26544. }
  26545. this.isPlaying = true;
  26546. this.startTime = this.game.time.now;
  26547. this.currentTime = 0;
  26548. this.stopTime = this.startTime + this.durationMS;
  26549. this.onPlay.dispatch(this);
  26550. }
  26551. else
  26552. {
  26553. this.pendingPlayback = true;
  26554. if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).isDecoding === false)
  26555. {
  26556. this.game.sound.decode(this.key, this);
  26557. }
  26558. }
  26559. }
  26560. else
  26561. {
  26562. // console.log('Sound play Audio');
  26563. if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).locked)
  26564. {
  26565. // console.log('tried playing locked sound, pending set, reload started');
  26566. this.game.cache.reloadSound(this.key);
  26567. this.pendingPlayback = true;
  26568. }
  26569. else
  26570. {
  26571. // console.log('sound not locked, state?', this._sound.readyState);
  26572. if (this._sound && this._sound.readyState == 4)
  26573. {
  26574. this._sound.play();
  26575. // This doesn't become available until you call play(), wonderful ...
  26576. this.totalDuration = this._sound.duration;
  26577. if (this.duration === 0)
  26578. {
  26579. this.duration = this.totalDuration;
  26580. this.durationMS = this.totalDuration * 1000;
  26581. }
  26582. // console.log('playing', this._sound);
  26583. this._sound.currentTime = this.position;
  26584. this._sound.muted = this._muted;
  26585. if (this._muted)
  26586. {
  26587. this._sound.volume = 0;
  26588. }
  26589. else
  26590. {
  26591. this._sound.volume = this._volume;
  26592. }
  26593. this.isPlaying = true;
  26594. this.startTime = this.game.time.now;
  26595. this.currentTime = 0;
  26596. this.stopTime = this.startTime + this.durationMS;
  26597. this.onPlay.dispatch(this);
  26598. }
  26599. else
  26600. {
  26601. this.pendingPlayback = true;
  26602. }
  26603. }
  26604. }
  26605. },
  26606. /**
  26607. * Restart the sound, or a marked section of it.
  26608. * @method Phaser.Sound#restart
  26609. * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
  26610. * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
  26611. * @param {number} [volume=1] - Volume of the sound you want to play.
  26612. * @param {boolean} [loop=false] - Loop when it finished playing?
  26613. */
  26614. restart: function (marker, position, volume, loop) {
  26615. marker = marker || '';
  26616. position = position || 0;
  26617. volume = volume || 1;
  26618. if (typeof loop == 'undefined') { loop = false; }
  26619. this.play(marker, position, volume, loop, true);
  26620. },
  26621. /**
  26622. * Pauses the sound
  26623. * @method Phaser.Sound#pause
  26624. */
  26625. pause: function () {
  26626. if (this.isPlaying && this._sound)
  26627. {
  26628. this.stop();
  26629. this.isPlaying = false;
  26630. this.paused = true;
  26631. this.pausedPosition = this.currentTime;
  26632. this.pausedTime = this.game.time.now;
  26633. this.onPause.dispatch(this);
  26634. }
  26635. },
  26636. /**
  26637. * Resumes the sound
  26638. * @method Phaser.Sound#resume
  26639. */
  26640. resume: function () {
  26641. if (this.paused && this._sound)
  26642. {
  26643. if (this.usingWebAudio)
  26644. {
  26645. var p = this.position + (this.pausedPosition / 1000);
  26646. this._sound = this.context.createBufferSource();
  26647. this._sound.buffer = this._buffer;
  26648. this._sound.connect(this.gainNode);
  26649. if (typeof this._sound.start === 'undefined')
  26650. {
  26651. this._sound.noteGrainOn(0, p, this.duration);
  26652. //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it
  26653. }
  26654. else
  26655. {
  26656. this._sound.start(0, p, this.duration);
  26657. }
  26658. }
  26659. else
  26660. {
  26661. this._sound.play();
  26662. }
  26663. this.isPlaying = true;
  26664. this.paused = false;
  26665. this.startTime += (this.game.time.now - this.pausedTime);
  26666. this.onResume.dispatch(this);
  26667. }
  26668. },
  26669. /**
  26670. * Stop playing this sound.
  26671. * @method Phaser.Sound#stop
  26672. */
  26673. stop: function () {
  26674. if (this.isPlaying && this._sound)
  26675. {
  26676. if (this.usingWebAudio)
  26677. {
  26678. if (typeof this._sound.stop === 'undefined')
  26679. {
  26680. this._sound.noteOff(0);
  26681. }
  26682. else
  26683. {
  26684. this._sound.stop(0);
  26685. }
  26686. }
  26687. else if (this.usingAudioTag)
  26688. {
  26689. this._sound.pause();
  26690. this._sound.currentTime = 0;
  26691. }
  26692. }
  26693. this.isPlaying = false;
  26694. var prevMarker = this.currentMarker;
  26695. this.currentMarker = '';
  26696. this.onStop.dispatch(this, prevMarker);
  26697. }
  26698. };
  26699. /**
  26700. * @name Phaser.Sound#isDecoding
  26701. * @property {boolean} isDecoding - Returns true if the sound file is still decoding.
  26702. * @readonly
  26703. */
  26704. Object.defineProperty(Phaser.Sound.prototype, "isDecoding", {
  26705. get: function () {
  26706. return this.game.cache.getSound(this.key).isDecoding;
  26707. }
  26708. });
  26709. /**
  26710. * @name Phaser.Sound#isDecoded
  26711. * @property {boolean} isDecoded - Returns true if the sound file has decoded.
  26712. * @readonly
  26713. */
  26714. Object.defineProperty(Phaser.Sound.prototype, "isDecoded", {
  26715. get: function () {
  26716. return this.game.cache.isSoundDecoded(this.key);
  26717. }
  26718. });
  26719. /**
  26720. * @name Phaser.Sound#mute
  26721. * @property {boolean} mute - Gets or sets the muted state of this sound.
  26722. */
  26723. Object.defineProperty(Phaser.Sound.prototype, "mute", {
  26724. get: function () {
  26725. return this._muted;
  26726. },
  26727. set: function (value) {
  26728. value = value || null;
  26729. if (value)
  26730. {
  26731. this._muted = true;
  26732. if (this.usingWebAudio)
  26733. {
  26734. this._muteVolume = this.gainNode.gain.value;
  26735. this.gainNode.gain.value = 0;
  26736. }
  26737. else if (this.usingAudioTag && this._sound)
  26738. {
  26739. this._muteVolume = this._sound.volume;
  26740. this._sound.volume = 0;
  26741. }
  26742. }
  26743. else
  26744. {
  26745. this._muted = false;
  26746. if (this.usingWebAudio)
  26747. {
  26748. this.gainNode.gain.value = this._muteVolume;
  26749. }
  26750. else if (this.usingAudioTag && this._sound)
  26751. {
  26752. this._sound.volume = this._muteVolume;
  26753. }
  26754. }
  26755. this.onMute.dispatch(this);
  26756. }
  26757. });
  26758. /**
  26759. * @name Phaser.Sound#volume
  26760. * @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1.
  26761. * @readonly
  26762. */
  26763. Object.defineProperty(Phaser.Sound.prototype, "volume", {
  26764. get: function () {
  26765. return this._volume;
  26766. },
  26767. set: function (value) {
  26768. if (this.usingWebAudio)
  26769. {
  26770. this._volume = value;
  26771. this.gainNode.gain.value = value;
  26772. }
  26773. else if (this.usingAudioTag && this._sound)
  26774. {
  26775. // Causes an Index size error in Firefox if you don't clamp the value
  26776. if (value >= 0 && value <= 1)
  26777. {
  26778. this._volume = value;
  26779. this._sound.volume = value;
  26780. }
  26781. }
  26782. }
  26783. });
  26784. /**
  26785. * @author Richard Davey <rich@photonstorm.com>
  26786. * @copyright 2013 Photon Storm Ltd.
  26787. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  26788. */
  26789. /**
  26790. * Sound Manager constructor.
  26791. * The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it.
  26792. * Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files.
  26793. *
  26794. * @class Phaser.SoundManager
  26795. * @classdesc Phaser Sound Manager.
  26796. * @constructor
  26797. * @param {Phaser.Game} game reference to the current game instance.
  26798. */
  26799. Phaser.SoundManager = function (game) {
  26800. /**
  26801. * @property {Phaser.Game} game - Local reference to game.
  26802. */
  26803. this.game = game;
  26804. /**
  26805. * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files)
  26806. */
  26807. this.onSoundDecode = new Phaser.Signal();
  26808. /**
  26809. * @property {boolean} _muted - Internal mute tracking var.
  26810. * @private
  26811. * @default
  26812. */
  26813. this._muted = false;
  26814. /**
  26815. * @property {Description} _unlockSource - Internal unlock tracking var.
  26816. * @private
  26817. * @default
  26818. */
  26819. this._unlockSource = null;
  26820. /**
  26821. * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
  26822. * @private
  26823. * @default
  26824. */
  26825. this._volume = 1;
  26826. /**
  26827. * @property {array} _sounds - An array containing all the sounds
  26828. * @private
  26829. * @default The empty array.
  26830. */
  26831. this._sounds = [];
  26832. /**
  26833. * @property {AudioContext} context - The AudioContext being used for playback.
  26834. * @default
  26835. */
  26836. this.context = null;
  26837. /**
  26838. * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio.
  26839. * @readonly
  26840. */
  26841. this.usingWebAudio = true;
  26842. /**
  26843. * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag.
  26844. * @readonly
  26845. */
  26846. this.usingAudioTag = false;
  26847. /**
  26848. * @property {boolean} noAudio - Has audio been disabled via the PhaserGlobal object? Useful if you need to use a 3rd party audio library instead.
  26849. * @default
  26850. */
  26851. this.noAudio = false;
  26852. /**
  26853. * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node.
  26854. * @default
  26855. */
  26856. this.connectToMaster = true;
  26857. /**
  26858. * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event.
  26859. * @default
  26860. */
  26861. this.touchLocked = false;
  26862. /**
  26863. * @property {number} channels - The number of audio channels to use in playback.
  26864. * @default
  26865. */
  26866. this.channels = 32;
  26867. };
  26868. Phaser.SoundManager.prototype = {
  26869. /**
  26870. * Initialises the sound manager.
  26871. * @method Phaser.SoundManager#boot
  26872. * @protected
  26873. */
  26874. boot: function () {
  26875. if (this.game.device.iOS && this.game.device.webAudio === false)
  26876. {
  26877. this.channels = 1;
  26878. }
  26879. if (this.game.device.iOS || (window['PhaserGlobal'] && window['PhaserGlobal'].fakeiOSTouchLock))
  26880. {
  26881. this.game.input.touch.callbackContext = this;
  26882. this.game.input.touch.touchStartCallback = this.unlock;
  26883. this.game.input.mouse.callbackContext = this;
  26884. this.game.input.mouse.mouseDownCallback = this.unlock;
  26885. this.touchLocked = true;
  26886. }
  26887. else
  26888. {
  26889. // What about iOS5?
  26890. this.touchLocked = false;
  26891. }
  26892. if (window['PhaserGlobal'])
  26893. {
  26894. // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class)
  26895. if (window['PhaserGlobal'].disableAudio === true)
  26896. {
  26897. this.usingWebAudio = false;
  26898. this.noAudio = true;
  26899. return;
  26900. }
  26901. // Check if the Web Audio API is disabled (for testing Audio Tag playback during development)
  26902. if (window['PhaserGlobal'].disableWebAudio === true)
  26903. {
  26904. this.usingWebAudio = false;
  26905. this.usingAudioTag = true;
  26906. this.noAudio = false;
  26907. return;
  26908. }
  26909. }
  26910. if (!!window['AudioContext'])
  26911. {
  26912. this.context = new window['AudioContext']();
  26913. }
  26914. else if (!!window['webkitAudioContext'])
  26915. {
  26916. this.context = new window['webkitAudioContext']();
  26917. }
  26918. else if (!!window['Audio'])
  26919. {
  26920. this.usingWebAudio = false;
  26921. this.usingAudioTag = true;
  26922. }
  26923. else
  26924. {
  26925. this.usingWebAudio = false;
  26926. this.noAudio = true;
  26927. }
  26928. if (this.context !== null)
  26929. {
  26930. if (typeof this.context.createGain === 'undefined')
  26931. {
  26932. this.masterGain = this.context.createGainNode();
  26933. }
  26934. else
  26935. {
  26936. this.masterGain = this.context.createGain();
  26937. }
  26938. this.masterGain.gain.value = 1;
  26939. this.masterGain.connect(this.context.destination);
  26940. }
  26941. },
  26942. /**
  26943. * Enables the audio, usually after the first touch.
  26944. * @method Phaser.SoundManager#unlock
  26945. */
  26946. unlock: function () {
  26947. if (this.touchLocked === false)
  26948. {
  26949. return;
  26950. }
  26951. // Global override (mostly for Audio Tag testing)
  26952. if (this.game.device.webAudio === false || (window['PhaserGlobal'] && window['PhaserGlobal'].disableWebAudio === true))
  26953. {
  26954. // Create an Audio tag?
  26955. this.touchLocked = false;
  26956. this._unlockSource = null;
  26957. this.game.input.touch.callbackContext = null;
  26958. this.game.input.touch.touchStartCallback = null;
  26959. this.game.input.mouse.callbackContext = null;
  26960. this.game.input.mouse.mouseDownCallback = null;
  26961. }
  26962. else
  26963. {
  26964. // Create empty buffer and play it
  26965. var buffer = this.context.createBuffer(1, 1, 22050);
  26966. this._unlockSource = this.context.createBufferSource();
  26967. this._unlockSource.buffer = buffer;
  26968. this._unlockSource.connect(this.context.destination);
  26969. this._unlockSource.noteOn(0);
  26970. }
  26971. },
  26972. /**
  26973. * Stops all the sounds in the game.
  26974. * @method Phaser.SoundManager#stopAll
  26975. */
  26976. stopAll: function () {
  26977. for (var i = 0; i < this._sounds.length; i++)
  26978. {
  26979. if (this._sounds[i])
  26980. {
  26981. this._sounds[i].stop();
  26982. }
  26983. }
  26984. },
  26985. /**
  26986. * Pauses all the sounds in the game.
  26987. * @method Phaser.SoundManager#pauseAll
  26988. */
  26989. pauseAll: function () {
  26990. for (var i = 0; i < this._sounds.length; i++)
  26991. {
  26992. if (this._sounds[i])
  26993. {
  26994. this._sounds[i].pause();
  26995. }
  26996. }
  26997. },
  26998. /**
  26999. * resumes every sound in the game.
  27000. * @method Phaser.SoundManager#resumeAll
  27001. */
  27002. resumeAll: function () {
  27003. for (var i = 0; i < this._sounds.length; i++)
  27004. {
  27005. if (this._sounds[i])
  27006. {
  27007. this._sounds[i].resume();
  27008. }
  27009. }
  27010. },
  27011. /**
  27012. * Decode a sound by its assets key.
  27013. * @method Phaser.SoundManager#decode
  27014. * @param {string} key - Assets key of the sound to be decoded.
  27015. * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data.
  27016. */
  27017. decode: function (key, sound) {
  27018. sound = sound || null;
  27019. var soundData = this.game.cache.getSoundData(key);
  27020. if (soundData)
  27021. {
  27022. if (this.game.cache.isSoundDecoded(key) === false)
  27023. {
  27024. this.game.cache.updateSound(key, 'isDecoding', true);
  27025. var that = this;
  27026. this.context.decodeAudioData(soundData, function (buffer) {
  27027. that.game.cache.decodedSound(key, buffer);
  27028. if (sound)
  27029. {
  27030. that.onSoundDecode.dispatch(sound);
  27031. }
  27032. });
  27033. }
  27034. }
  27035. },
  27036. /**
  27037. * Updates every sound in the game.
  27038. * @method Phaser.SoundManager#update
  27039. */
  27040. update: function () {
  27041. if (this.touchLocked)
  27042. {
  27043. if (this.game.device.webAudio && this._unlockSource !== null)
  27044. {
  27045. if ((this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE))
  27046. {
  27047. this.touchLocked = false;
  27048. this._unlockSource = null;
  27049. this.game.input.touch.callbackContext = null;
  27050. this.game.input.touch.touchStartCallback = null;
  27051. }
  27052. }
  27053. }
  27054. for (var i = 0; i < this._sounds.length; i++)
  27055. {
  27056. this._sounds[i].update();
  27057. }
  27058. },
  27059. /**
  27060. * Adds a new Sound into the SoundManager.
  27061. * @method Phaser.SoundManager#add
  27062. * @param {string} key - Asset key for the sound.
  27063. * @param {number} [volume=1] - Default value for the volume.
  27064. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  27065. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  27066. * @return {Phaser.Sound} The new sound instance.
  27067. */
  27068. add: function (key, volume, loop, connect) {
  27069. if (typeof volume === 'undefined') { volume = 1; }
  27070. if (typeof loop === 'undefined') { loop = false; }
  27071. if (typeof connect === 'undefined') { connect = this.connectToMaster; }
  27072. var sound = new Phaser.Sound(this.game, key, volume, loop, connect);
  27073. this._sounds.push(sound);
  27074. return sound;
  27075. },
  27076. /**
  27077. * Adds a new Sound into the SoundManager and starts it playing.
  27078. * @method Phaser.SoundManager#play
  27079. * @param {string} key - Asset key for the sound.
  27080. * @param {number} [volume=1] - Default value for the volume.
  27081. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  27082. * @param {boolean} [destroyOnComplete=false] - If true the Sound will destroy itself once it has finished playing, or is stopped.
  27083. * @return {Phaser.Sound} The new sound instance.
  27084. */
  27085. play: function (key, volume, loop, destroyOnComplete) {
  27086. if (typeof destroyOnComplete == 'undefined') { destroyOnComplete = false; }
  27087. var sound = this.add(key, volume, loop);
  27088. sound.play();
  27089. return sound;
  27090. }
  27091. };
  27092. /**
  27093. * @name Phaser.SoundManager#mute
  27094. * @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game.
  27095. */
  27096. Object.defineProperty(Phaser.SoundManager.prototype, "mute", {
  27097. get: function () {
  27098. return this._muted;
  27099. },
  27100. set: function (value) {
  27101. value = value || null;
  27102. if (value)
  27103. {
  27104. if (this._muted)
  27105. {
  27106. return;
  27107. }
  27108. this._muted = true;
  27109. if (this.usingWebAudio)
  27110. {
  27111. this._muteVolume = this.masterGain.gain.value;
  27112. this.masterGain.gain.value = 0;
  27113. }
  27114. // Loop through sounds
  27115. for (var i = 0; i < this._sounds.length; i++)
  27116. {
  27117. if (this._sounds[i].usingAudioTag)
  27118. {
  27119. this._sounds[i].mute = true;
  27120. }
  27121. }
  27122. }
  27123. else
  27124. {
  27125. if (this._muted === false)
  27126. {
  27127. return;
  27128. }
  27129. this._muted = false;
  27130. if (this.usingWebAudio)
  27131. {
  27132. this.masterGain.gain.value = this._muteVolume;
  27133. }
  27134. // Loop through sounds
  27135. for (var i = 0; i < this._sounds.length; i++)
  27136. {
  27137. if (this._sounds[i].usingAudioTag)
  27138. {
  27139. this._sounds[i].mute = false;
  27140. }
  27141. }
  27142. }
  27143. }
  27144. });
  27145. /**
  27146. * @name Phaser.SoundManager#volume
  27147. * @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1.
  27148. */
  27149. Object.defineProperty(Phaser.SoundManager.prototype, "volume", {
  27150. get: function () {
  27151. if (this.usingWebAudio)
  27152. {
  27153. return this.masterGain.gain.value;
  27154. }
  27155. else
  27156. {
  27157. return this._volume;
  27158. }
  27159. },
  27160. set: function (value) {
  27161. value = this.game.math.clamp(value, 1, 0);
  27162. this._volume = value;
  27163. if (this.usingWebAudio)
  27164. {
  27165. this.masterGain.gain.value = value;
  27166. }
  27167. // Loop through the sound cache and change the volume of all html audio tags
  27168. for (var i = 0; i < this._sounds.length; i++)
  27169. {
  27170. if (this._sounds[i].usingAudioTag)
  27171. {
  27172. this._sounds[i].volume = this._sounds[i].volume * value;
  27173. }
  27174. }
  27175. }
  27176. });
  27177. /**
  27178. * @author Richard Davey <rich@photonstorm.com>
  27179. * @copyright 2013 Photon Storm Ltd.
  27180. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  27181. */
  27182. /**
  27183. * A collection of methods for displaying debug information about game objects. Phaser.Debug requires a CANVAS game type in order to render, so if you've got
  27184. * your game set to use Phaser.AUTO then swap it for Phaser.CANVAS to ensure WebGL doesn't kick in, then the Debug functions will all display.
  27185. *
  27186. * @class Phaser.Utils.Debug
  27187. * @constructor
  27188. * @param {Phaser.Game} game - A reference to the currently running game.
  27189. */
  27190. Phaser.Utils.Debug = function (game) {
  27191. /**
  27192. * @property {Phaser.Game} game - A reference to the currently running Game.
  27193. */
  27194. this.game = game;
  27195. /**
  27196. * @property {Context} context - The canvas context on which to render the debug information.
  27197. */
  27198. this.context = game.context;
  27199. /**
  27200. * @property {string} font - The font that the debug information is rendered in.
  27201. * @default '14px Courier'
  27202. */
  27203. this.font = '14px Courier';
  27204. /**
  27205. * @property {number} lineHeight - The line height between the debug text.
  27206. */
  27207. this.lineHeight = 16;
  27208. /**
  27209. * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background.
  27210. */
  27211. this.renderShadow = true;
  27212. /**
  27213. * @property {Context} currentX - The current X position the debug information will be rendered at.
  27214. * @default
  27215. */
  27216. this.currentX = 0;
  27217. /**
  27218. * @property {number} currentY - The current Y position the debug information will be rendered at.
  27219. * @default
  27220. */
  27221. this.currentY = 0;
  27222. /**
  27223. * @property {number} currentAlpha - The current alpha the debug information will be rendered at.
  27224. * @default
  27225. */
  27226. this.currentAlpha = 1;
  27227. };
  27228. Phaser.Utils.Debug.prototype = {
  27229. /**
  27230. * Internal method that resets and starts the debug output values.
  27231. * @method Phaser.Utils.Debug#start
  27232. * @param {number} x - The X value the debug info will start from.
  27233. * @param {number} y - The Y value the debug info will start from.
  27234. * @param {string} color - The color the debug info will drawn in.
  27235. */
  27236. start: function (x, y, color) {
  27237. if (this.context == null)
  27238. {
  27239. return;
  27240. }
  27241. if (typeof x !== 'number') { x = 0; }
  27242. if (typeof y !== 'number') { y = 0; }
  27243. color = color || 'rgb(255,255,255)';
  27244. this.currentX = x;
  27245. this.currentY = y;
  27246. this.currentColor = color;
  27247. this.currentAlpha = this.context.globalAlpha;
  27248. this.context.save();
  27249. this.context.setTransform(1, 0, 0, 1, 0, 0);
  27250. this.context.fillStyle = color;
  27251. this.context.font = this.font;
  27252. this.context.globalAlpha = 1;
  27253. },
  27254. /**
  27255. * Internal method that stops the debug output.
  27256. * @method Phaser.Utils.Debug#stop
  27257. */
  27258. stop: function () {
  27259. this.context.restore();
  27260. this.context.globalAlpha = this.currentAlpha;
  27261. },
  27262. /**
  27263. * Internal method that outputs a single line of text.
  27264. * @method Phaser.Utils.Debug#line
  27265. * @param {string} text - The line of text to draw.
  27266. * @param {number} x - The X value the debug info will start from.
  27267. * @param {number} y - The Y value the debug info will start from.
  27268. */
  27269. line: function (text, x, y) {
  27270. if (this.context == null)
  27271. {
  27272. return;
  27273. }
  27274. x = x || null;
  27275. y = y || null;
  27276. if (x !== null) {
  27277. this.currentX = x;
  27278. }
  27279. if (y !== null) {
  27280. this.currentY = y;
  27281. }
  27282. if (this.renderShadow)
  27283. {
  27284. this.context.fillStyle = 'rgb(0,0,0)';
  27285. this.context.fillText(text, this.currentX + 1, this.currentY + 1);
  27286. this.context.fillStyle = this.currentColor;
  27287. }
  27288. this.context.fillText(text, this.currentX, this.currentY);
  27289. this.currentY += this.lineHeight;
  27290. },
  27291. /**
  27292. * Visually renders a QuadTree to the display.
  27293. * @method Phaser.Utils.Debug#renderQuadTree
  27294. * @param {Phaser.QuadTree} quadtree - The quadtree to render.
  27295. * @param {string} color - The color of the lines in the quadtree.
  27296. */
  27297. renderQuadTree: function (quadtree, color) {
  27298. color = color || 'rgba(255,0,0,0.3)';
  27299. this.start();
  27300. var bounds = quadtree.bounds;
  27301. if (quadtree.nodes.length === 0)
  27302. {
  27303. this.context.strokeStyle = color;
  27304. this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height);
  27305. this.renderText(quadtree.ID + ' / ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier');
  27306. this.context.strokeStyle = 'rgb(0,255,0)';
  27307. // children
  27308. for (var i = 0; i < quadtree.objects.length; i++)
  27309. {
  27310. this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height);
  27311. }
  27312. }
  27313. else
  27314. {
  27315. for (var i = 0; i < quadtree.nodes.length; i++)
  27316. {
  27317. this.renderQuadTree(quadtree.nodes[i]);
  27318. }
  27319. }
  27320. this.stop();
  27321. },
  27322. /**
  27323. * Renders the corners and point information of the given Sprite.
  27324. * @method Phaser.Utils.Debug#renderSpriteCorners
  27325. * @param {Phaser.Sprite} sprite - The sprite to be rendered.
  27326. * @param {boolean} [showText=false] - If true the x/y coordinates of each point will be rendered.
  27327. * @param {boolean} [showBounds=false] - If true the bounds will be rendered over the top of the sprite.
  27328. * @param {string} [color='rgb(255,0,255)'] - The color the text is rendered in.
  27329. */
  27330. renderSpriteCorners: function (sprite, showText, showBounds, color) {
  27331. if (this.context == null)
  27332. {
  27333. return;
  27334. }
  27335. showText = showText || false;
  27336. showBounds = showBounds || false;
  27337. color = color || 'rgb(255,255,255)';
  27338. this.start(0, 0, color);
  27339. if (showBounds)
  27340. {
  27341. this.context.beginPath();
  27342. this.context.strokeStyle = 'rgba(0, 255, 0, 0.7)';
  27343. this.context.strokeRect(sprite.bounds.x, sprite.bounds.y, sprite.bounds.width, sprite.bounds.height);
  27344. this.context.closePath();
  27345. this.context.stroke();
  27346. }
  27347. this.context.beginPath();
  27348. this.context.moveTo(sprite.topLeft.x, sprite.topLeft.y);
  27349. this.context.lineTo(sprite.topRight.x, sprite.topRight.y);
  27350. this.context.lineTo(sprite.bottomRight.x, sprite.bottomRight.y);
  27351. this.context.lineTo(sprite.bottomLeft.x, sprite.bottomLeft.y);
  27352. this.context.closePath();
  27353. this.context.strokeStyle = 'rgba(255, 0, 255, 0.7)';
  27354. this.context.stroke();
  27355. this.renderPoint(sprite.offset);
  27356. this.renderPoint(sprite.center);
  27357. this.renderPoint(sprite.topLeft);
  27358. this.renderPoint(sprite.topRight);
  27359. this.renderPoint(sprite.bottomLeft);
  27360. this.renderPoint(sprite.bottomRight);
  27361. if (showText)
  27362. {
  27363. this.currentColor = color;
  27364. this.line('x: ' + Math.floor(sprite.topLeft.x) + ' y: ' + Math.floor(sprite.topLeft.y), sprite.topLeft.x, sprite.topLeft.y);
  27365. this.line('x: ' + Math.floor(sprite.topRight.x) + ' y: ' + Math.floor(sprite.topRight.y), sprite.topRight.x, sprite.topRight.y);
  27366. this.line('x: ' + Math.floor(sprite.bottomLeft.x) + ' y: ' + Math.floor(sprite.bottomLeft.y), sprite.bottomLeft.x, sprite.bottomLeft.y);
  27367. this.line('x: ' + Math.floor(sprite.bottomRight.x) + ' y: ' + Math.floor(sprite.bottomRight.y), sprite.bottomRight.x, sprite.bottomRight.y);
  27368. }
  27369. this.stop();
  27370. },
  27371. /**
  27372. * Render Sound information, including decoded state, duration, volume and more.
  27373. * @method Phaser.Utils.Debug#renderSoundInfo
  27374. * @param {Phaser.Sound} sound - The sound object to debug.
  27375. * @param {number} x - X position of the debug info to be rendered.
  27376. * @param {number} y - Y position of the debug info to be rendered.
  27377. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  27378. */
  27379. renderSoundInfo: function (sound, x, y, color) {
  27380. if (this.context == null)
  27381. {
  27382. return;
  27383. }
  27384. color = color || 'rgb(255,255,255)';
  27385. this.start(x, y, color);
  27386. this.line('Sound: ' + sound.key + ' Locked: ' + sound.game.sound.touchLocked);
  27387. this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback);
  27388. this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding);
  27389. this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying);
  27390. this.line('Time: ' + sound.currentTime);
  27391. this.line('Volume: ' + sound.volume + ' Muted: ' + sound.mute);
  27392. this.line('WebAudio: ' + sound.usingWebAudio + ' Audio: ' + sound.usingAudioTag);
  27393. if (sound.currentMarker !== '')
  27394. {
  27395. this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration);
  27396. this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop);
  27397. this.line('Position: ' + sound.position);
  27398. }
  27399. this.stop();
  27400. },
  27401. /**
  27402. * Render camera information including dimensions and location.
  27403. * @method Phaser.Utils.Debug#renderCameraInfo
  27404. * @param {Phaser.Camera} camera - Description.
  27405. * @param {number} x - X position of the debug info to be rendered.
  27406. * @param {number} y - Y position of the debug info to be rendered.
  27407. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  27408. */
  27409. renderCameraInfo: function (camera, x, y, color) {
  27410. if (this.context == null)
  27411. {
  27412. return;
  27413. }
  27414. color = color || 'rgb(255,255,255)';
  27415. this.start(x, y, color);
  27416. this.line('Camera (' + camera.width + ' x ' + camera.height + ')');
  27417. this.line('X: ' + camera.x + ' Y: ' + camera.y);
  27418. this.line('Bounds x: ' + camera.bounds.x + ' Y: ' + camera.bounds.y + ' w: ' + camera.bounds.width + ' h: ' + camera.bounds.height);
  27419. this.line('View x: ' + camera.view.x + ' Y: ' + camera.view.y + ' w: ' + camera.view.width + ' h: ' + camera.view.height);
  27420. this.stop();
  27421. },
  27422. /**
  27423. * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text.
  27424. * @method Phaser.Utils.Debug#renderPointer
  27425. * @param {Phaser.Pointer} pointer - Description.
  27426. * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up.
  27427. * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down.
  27428. * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false).
  27429. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  27430. */
  27431. renderPointer: function (pointer, hideIfUp, downColor, upColor, color) {
  27432. if (this.context == null || pointer == null)
  27433. {
  27434. return;
  27435. }
  27436. if (typeof hideIfUp === 'undefined') { hideIfUp = false; }
  27437. downColor = downColor || 'rgba(0,255,0,0.5)';
  27438. upColor = upColor || 'rgba(255,0,0,0.5)';
  27439. color = color || 'rgb(255,255,255)';
  27440. if (hideIfUp === true && pointer.isUp === true)
  27441. {
  27442. return;
  27443. }
  27444. this.start(pointer.x, pointer.y - 100, color);
  27445. this.context.beginPath();
  27446. this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2);
  27447. if (pointer.active)
  27448. {
  27449. this.context.fillStyle = downColor;
  27450. }
  27451. else
  27452. {
  27453. this.context.fillStyle = upColor;
  27454. }
  27455. this.context.fill();
  27456. this.context.closePath();
  27457. // Render the points
  27458. this.context.beginPath();
  27459. this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y);
  27460. this.context.lineTo(pointer.position.x, pointer.position.y);
  27461. this.context.lineWidth = 2;
  27462. this.context.stroke();
  27463. this.context.closePath();
  27464. // Render the text
  27465. // this.start(pointer.x, pointer.y - 100, color);
  27466. this.line('ID: ' + pointer.id + " Active: " + pointer.active);
  27467. this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY);
  27468. this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y);
  27469. this.line('Duration: ' + pointer.duration + " ms");
  27470. this.stop();
  27471. },
  27472. /**
  27473. * Render Sprite Input Debug information.
  27474. * @method Phaser.Utils.Debug#renderSpriteInputInfo
  27475. * @param {Phaser.Sprite} sprite - The sprite to be rendered.
  27476. * @param {number} x - X position of the debug info to be rendered.
  27477. * @param {number} y - Y position of the debug info to be rendered.
  27478. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  27479. */
  27480. renderSpriteInputInfo: function (sprite, x, y, color) {
  27481. color = color || 'rgb(255,255,255)';
  27482. this.start(x, y, color);
  27483. this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')');
  27484. this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1));
  27485. this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0));
  27486. this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0));
  27487. this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut());
  27488. this.stop();
  27489. },
  27490. /**
  27491. * Render Sprite collision.
  27492. * @method Phaser.Utils.Debug#renderSpriteCollision
  27493. * @param {Phaser.Sprite} sprite - The sprite to be rendered.
  27494. * @param {number} x - X position of the debug info to be rendered.
  27495. * @param {number} y - Y position of the debug info to be rendered.
  27496. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  27497. */
  27498. renderSpriteCollision: function (sprite, x, y, color) {
  27499. color = color || 'rgb(255,255,255)';
  27500. this.start(x, y, color);
  27501. this.line('Sprite Collision: (' + sprite.width + ' x ' + sprite.height + ')');
  27502. this.line('left: ' + sprite.body.touching.left);
  27503. this.line('right: ' + sprite.body.touching.right);
  27504. this.line('up: ' + sprite.body.touching.up);
  27505. this.line('down: ' + sprite.body.touching.down);
  27506. this.line('velocity.x: ' + sprite.body.velocity.x);
  27507. this.line('velocity.y: ' + sprite.body.velocity.y);
  27508. this.stop();
  27509. },
  27510. /**
  27511. * Render debug information about the Input object.
  27512. * @method Phaser.Utils.Debug#renderInputInfo
  27513. * @param {number} x - X position of the debug info to be rendered.
  27514. * @param {number} y - Y position of the debug info to be rendered.
  27515. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  27516. */
  27517. renderInputInfo: function (x, y, color) {
  27518. if (this.context == null)
  27519. {
  27520. return;
  27521. }
  27522. color = color || 'rgb(255,255,0)';
  27523. this.start(x, y, color);
  27524. this.line('Input');
  27525. this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y);
  27526. this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY);
  27527. this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1));
  27528. this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY);
  27529. this.stop();
  27530. },
  27531. /**
  27532. * Render debug infos (including name, bounds info, position and some other properties) about the Sprite.
  27533. * @method Phaser.Utils.Debug#renderSpriteInfo
  27534. * @param {Phaser.Sprite} sprite - Description.
  27535. * @param {number} x - X position of the debug info to be rendered.
  27536. * @param {number} y - Y position of the debug info to be rendered.
  27537. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  27538. */
  27539. renderSpriteInfo: function (sprite, x, y, color) {
  27540. if (this.context == null)
  27541. {
  27542. return;
  27543. }
  27544. color = color || 'rgb(255, 255, 255)';
  27545. this.start(x, y, color);
  27546. this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y);
  27547. this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1));
  27548. this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1));
  27549. this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera);
  27550. this.line('body x: ' + sprite.body.x.toFixed(1) + ' y: ' + sprite.body.y.toFixed(1));
  27551. // 0 = scaleX
  27552. // 1 = skewY
  27553. // 2 = translateX
  27554. // 3 = skewX
  27555. // 4 = scaleY
  27556. // 5 = translateY
  27557. // this.line('id: ' + sprite._id);
  27558. // this.line('scale x: ' + sprite.worldTransform[0]);
  27559. // this.line('scale y: ' + sprite.worldTransform[4]);
  27560. // this.line('tx: ' + sprite.worldTransform[2]);
  27561. // this.line('ty: ' + sprite.worldTransform[5]);
  27562. // this.line('skew x: ' + sprite.worldTransform[3]);
  27563. // this.line('skew y: ' + sprite.worldTransform[1]);
  27564. this.line('deltaX: ' + sprite.body.deltaX());
  27565. this.line('deltaY: ' + sprite.body.deltaY());
  27566. // this.line('sdx: ' + sprite.deltaX());
  27567. // this.line('sdy: ' + sprite.deltaY());
  27568. // this.line('inCamera: ' + this.game.renderer.spriteRenderer.inCamera(this.game.camera, sprite));
  27569. this.stop();
  27570. },
  27571. /**
  27572. * Render the World Transform information of the given Sprite.
  27573. * @method Phaser.Utils.Debug#renderWorldTransformInfo
  27574. * @param {Phaser.Sprite} sprite - Description.
  27575. * @param {number} x - X position of the debug info to be rendered.
  27576. * @param {number} y - Y position of the debug info to be rendered.
  27577. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  27578. */
  27579. renderWorldTransformInfo: function (sprite, x, y, color) {
  27580. if (this.context == null)
  27581. {
  27582. return;
  27583. }
  27584. color = color || 'rgb(255, 255, 255)';
  27585. this.start(x, y, color);
  27586. this.line('World Transform');
  27587. this.line('skewX: ' + sprite.worldTransform[3]);
  27588. this.line('skewY: ' + sprite.worldTransform[1]);
  27589. this.line('scaleX: ' + sprite.worldTransform[0]);
  27590. this.line('scaleY: ' + sprite.worldTransform[4]);
  27591. this.line('transX: ' + sprite.worldTransform[2]);
  27592. this.line('transY: ' + sprite.worldTransform[5]);
  27593. this.stop();
  27594. },
  27595. /**
  27596. * Render the Local Transform information of the given Sprite.
  27597. * @method Phaser.Utils.Debug#renderLocalTransformInfo
  27598. * @param {Phaser.Sprite} sprite - Description.
  27599. * @param {number} x - X position of the debug info to be rendered.
  27600. * @param {number} y - Y position of the debug info to be rendered.
  27601. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  27602. */
  27603. renderLocalTransformInfo: function (sprite, x, y, color) {
  27604. if (this.context == null)
  27605. {
  27606. return;
  27607. }
  27608. color = color || 'rgb(255, 255, 255)';
  27609. this.start(x, y, color);
  27610. this.line('Local Transform');
  27611. this.line('skewX: ' + sprite.localTransform[3]);
  27612. this.line('skewY: ' + sprite.localTransform[1]);
  27613. this.line('scaleX: ' + sprite.localTransform[0]);
  27614. this.line('scaleY: ' + sprite.localTransform[4]);
  27615. this.line('transX: ' + sprite.localTransform[2]);
  27616. this.line('transY: ' + sprite.localTransform[5]);
  27617. this.stop();
  27618. },
  27619. renderSpriteCoords: function (sprite, x, y, color) {
  27620. if (this.context == null)
  27621. {
  27622. return;
  27623. }
  27624. color = color || 'rgb(255, 255, 255)';
  27625. this.start(x, y, color);
  27626. if (sprite.name)
  27627. {
  27628. this.line(sprite.name);
  27629. }
  27630. this.line('x: ' + sprite.x);
  27631. this.line('y: ' + sprite.y);
  27632. this.line('pos x: ' + sprite.position.x);
  27633. this.line('pos y: ' + sprite.position.y);
  27634. this.line('local x: ' + sprite.localTransform[2]);
  27635. this.line('local y: ' + sprite.localTransform[5]);
  27636. this.line('t x: ' + sprite.worldTransform[2]);
  27637. this.line('t y: ' + sprite.worldTransform[5]);
  27638. this.line('world x: ' + sprite.world.x);
  27639. this.line('world y: ' + sprite.world.y);
  27640. this.stop();
  27641. },
  27642. renderGroupInfo: function (group, x, y, color) {
  27643. if (this.context == null)
  27644. {
  27645. return;
  27646. }
  27647. color = color || 'rgb(255, 255, 255)';
  27648. this.start(x, y, color);
  27649. this.line('Group (size: ' + group.length + ')');
  27650. this.line('x: ' + group.x);
  27651. this.line('y: ' + group.y);
  27652. this.stop();
  27653. },
  27654. /**
  27655. * Renders Point coordinates in the given color.
  27656. * @method Phaser.Utils.Debug#renderPointInfo
  27657. * @param {Phaser.Point} sprite - Description.
  27658. * @param {number} x - X position of the debug info to be rendered.
  27659. * @param {number} y - Y position of the debug info to be rendered.
  27660. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  27661. */
  27662. renderPointInfo: function (point, x, y, color) {
  27663. if (this.context == null)
  27664. {
  27665. return;
  27666. }
  27667. color = color || 'rgb(255, 255, 255)';
  27668. this.start(x, y, color);
  27669. this.line('px: ' + point.x.toFixed(1) + ' py: ' + point.y.toFixed(1));
  27670. this.stop();
  27671. },
  27672. /**
  27673. * Renders just the Sprite.body bounds.
  27674. * @method Phaser.Utils.Debug#renderSpriteBody
  27675. * @param {Phaser.Sprite} sprite - Description.
  27676. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  27677. */
  27678. renderSpriteBody: function (sprite, color) {
  27679. if (this.context == null)
  27680. {
  27681. return;
  27682. }
  27683. color = color || 'rgba(255,0,255, 0.3)';
  27684. this.start(0, 0, color);
  27685. this.context.fillStyle = color;
  27686. this.context.fillRect(sprite.body.screenX, sprite.body.screenY, sprite.body.width, sprite.body.height);
  27687. this.stop();
  27688. },
  27689. /**
  27690. * Renders just the full Sprite bounds.
  27691. * @method Phaser.Utils.Debug#renderSpriteBounds
  27692. * @param {Phaser.Sprite} sprite - Description.
  27693. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  27694. * @param {boolean} [fill=false] - If false the bounds outline is rendered, if true the whole rectangle is rendered.
  27695. */
  27696. renderSpriteBounds: function (sprite, color, fill) {
  27697. if (this.context == null)
  27698. {
  27699. return;
  27700. }
  27701. color = color || 'rgb(255,0,255)';
  27702. if (typeof fill === 'undefined') { fill = false; }
  27703. this.start(0, 0, color);
  27704. if (fill)
  27705. {
  27706. this.context.fillStyle = color;
  27707. this.context.fillRect(sprite.bounds.x, sprite.bounds.y, sprite.bounds.width, sprite.bounds.height);
  27708. }
  27709. else
  27710. {
  27711. this.context.strokeStyle = color;
  27712. this.context.strokeRect(sprite.bounds.x, sprite.bounds.y, sprite.bounds.width, sprite.bounds.height);
  27713. this.context.stroke();
  27714. }
  27715. this.stop();
  27716. },
  27717. /**
  27718. * Renders a single pixel.
  27719. * @method Phaser.Utils.Debug#renderPixel
  27720. * @param {number} x - X position of the debug info to be rendered.
  27721. * @param {number} y - Y position of the debug info to be rendered.
  27722. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  27723. */
  27724. renderPixel: function (x, y, color) {
  27725. if (this.context == null)
  27726. {
  27727. return;
  27728. }
  27729. color = color || 'rgba(0,255,0,1)';
  27730. this.start();
  27731. this.context.fillStyle = color;
  27732. this.context.fillRect(x, y, 2, 2);
  27733. this.stop();
  27734. },
  27735. /**
  27736. * Renders a Point object.
  27737. * @method Phaser.Utils.Debug#renderPoint
  27738. * @param {Phaser.Point} point - The Point to render.
  27739. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  27740. */
  27741. renderPoint: function (point, color) {
  27742. if (this.context == null)
  27743. {
  27744. return;
  27745. }
  27746. color = color || 'rgba(0,255,0,1)';
  27747. this.start();
  27748. this.context.fillStyle = color;
  27749. this.context.fillRect(point.x, point.y, 4, 4);
  27750. this.stop();
  27751. },
  27752. /**
  27753. * Renders a Rectangle.
  27754. * @method Phaser.Utils.Debug#renderRectangle
  27755. * @param {Phaser.Rectangle} rect - The Rectangle to render.
  27756. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  27757. */
  27758. renderRectangle: function (rect, color) {
  27759. if (this.context == null)
  27760. {
  27761. return;
  27762. }
  27763. color = color || 'rgba(0,255,0,0.3)';
  27764. this.start();
  27765. this.context.fillStyle = color;
  27766. this.context.fillRect(rect.x, rect.y, rect.width, rect.height);
  27767. this.stop();
  27768. },
  27769. /**
  27770. * Renders a Circle.
  27771. * @method Phaser.Utils.Debug#renderCircle
  27772. * @param {Phaser.Circle} circle - The Circle to render.
  27773. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  27774. */
  27775. renderCircle: function (circle, color) {
  27776. if (this.context == null)
  27777. {
  27778. return;
  27779. }
  27780. color = color || 'rgba(0,255,0,0.3)';
  27781. this.start();
  27782. this.context.beginPath();
  27783. this.context.fillStyle = color;
  27784. this.context.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2, false);
  27785. this.context.fill();
  27786. this.context.closePath();
  27787. this.stop();
  27788. },
  27789. /**
  27790. * Render text.
  27791. * @method Phaser.Utils.Debug#renderText
  27792. * @param {string} text - The line of text to draw.
  27793. * @param {number} x - X position of the debug info to be rendered.
  27794. * @param {number} y - Y position of the debug info to be rendered.
  27795. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  27796. * @param {string} font - The font of text to draw.
  27797. */
  27798. renderText: function (text, x, y, color, font) {
  27799. if (this.context == null)
  27800. {
  27801. return;
  27802. }
  27803. color = color || 'rgb(255,255,255)';
  27804. font = font || '16px Courier';
  27805. this.start();
  27806. this.context.font = font;
  27807. this.context.fillStyle = color;
  27808. this.context.fillText(text, x, y);
  27809. this.stop();
  27810. },
  27811. /**
  27812. * Dumps the Linked List to the console.
  27813. *
  27814. * @method Phaser.Utils.Debug#Phaser.LinkedList#dump
  27815. * @param {Phaser.LinkedList} list - The LinkedList to dump.
  27816. */
  27817. dumpLinkedList: function (list) {
  27818. var spacing = 20;
  27819. var output = "\n" + Phaser.Utils.pad('Node', spacing) + "|" + Phaser.Utils.pad('Next', spacing) + "|" + Phaser.Utils.pad('Previous', spacing) + "|" + Phaser.Utils.pad('First', spacing) + "|" + Phaser.Utils.pad('Last', spacing);
  27820. console.log(output);
  27821. var output = Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing);
  27822. console.log(output);
  27823. var entity = list;
  27824. var testObject = entity.last.next;
  27825. entity = entity.first;
  27826. do
  27827. {
  27828. var name = entity.sprite.name || '*';
  27829. var nameNext = '-';
  27830. var namePrev = '-';
  27831. var nameFirst = '-';
  27832. var nameLast = '-';
  27833. if (entity.next)
  27834. {
  27835. nameNext = entity.next.sprite.name;
  27836. }
  27837. if (entity.prev)
  27838. {
  27839. namePrev = entity.prev.sprite.name;
  27840. }
  27841. if (entity.first)
  27842. {
  27843. nameFirst = entity.first.sprite.name;
  27844. }
  27845. if (entity.last)
  27846. {
  27847. nameLast = entity.last.sprite.name;
  27848. }
  27849. if (typeof nameNext === 'undefined')
  27850. {
  27851. nameNext = '-';
  27852. }
  27853. if (typeof namePrev === 'undefined')
  27854. {
  27855. namePrev = '-';
  27856. }
  27857. if (typeof nameFirst === 'undefined')
  27858. {
  27859. nameFirst = '-';
  27860. }
  27861. if (typeof nameLast === 'undefined')
  27862. {
  27863. nameLast = '-';
  27864. }
  27865. var output = Phaser.Utils.pad(name, spacing) + "|" + Phaser.Utils.pad(nameNext, spacing) + "|" + Phaser.Utils.pad(namePrev, spacing) + "|" + Phaser.Utils.pad(nameFirst, spacing) + "|" + Phaser.Utils.pad(nameLast, spacing);
  27866. console.log(output);
  27867. entity = entity.next;
  27868. }
  27869. while(entity != testObject)
  27870. }
  27871. };
  27872. /**
  27873. * @author Richard Davey <rich@photonstorm.com>
  27874. * @copyright 2013 Photon Storm Ltd.
  27875. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  27876. */
  27877. /**
  27878. * A collection of methods useful for manipulating and comparing colors.
  27879. *
  27880. * @class Phaser.Color
  27881. */
  27882. Phaser.Color = {
  27883. /**
  27884. * Given an alpha and 3 color values this will return an integer representation of it.
  27885. *
  27886. * @method Phaser.Color.getColor32
  27887. * @static
  27888. * @param {number} alpha - The Alpha value (between 0 and 255).
  27889. * @param {number} red - The Red channel value (between 0 and 255).
  27890. * @param {number} green - The Green channel value (between 0 and 255).
  27891. * @param {number} blue - The Blue channel value (between 0 and 255).
  27892. * @returns {number} A native color value integer (format: 0xAARRGGBB).
  27893. */
  27894. getColor32: function (alpha, red, green, blue) {
  27895. return alpha << 24 | red << 16 | green << 8 | blue;
  27896. },
  27897. /**
  27898. * Given 3 color values this will return an integer representation of it.
  27899. *
  27900. * @method Phaser.Color.getColor
  27901. * @static
  27902. * @param {number} red - The Red channel value (between 0 and 255).
  27903. * @param {number} green - The Green channel value (between 0 and 255).
  27904. * @param {number} blue - The Blue channel value (between 0 and 255).
  27905. * @returns {number} A native color value integer (format: 0xRRGGBB).
  27906. */
  27907. getColor: function (red, green, blue) {
  27908. return red << 16 | green << 8 | blue;
  27909. },
  27910. /**
  27911. * Converts the given hex string into an integer color value.
  27912. *
  27913. * @method Phaser.Color.hexToRGB
  27914. * @static
  27915. * @param {string} h - The string hex color to convert.
  27916. * @returns {number} The rgb color value.
  27917. */
  27918. hexToRGB: function (h) {
  27919. var hex16 = (h.charAt(0) == "#") ? h.substring(1, 7) : h;
  27920. if (hex16.length==3)
  27921. {
  27922. hex16 = hex16.charAt(0) + hex16.charAt(0) + hex16.charAt(1) + hex16.charAt(1) + hex16.charAt(2) + hex16.charAt(2);
  27923. }
  27924. var red = parseInt(hex16.substring(0, 2), 16);
  27925. var green = parseInt(hex16.substring(2, 4), 16);
  27926. var blue = parseInt(hex16.substring(4, 6), 16);
  27927. return red << 16 | green << 8 | blue;
  27928. },
  27929. /**
  27930. * Returns a string containing handy information about the given color including string hex value,
  27931. * RGB format information and HSL information. Each section starts on a newline, 3 lines in total.
  27932. *
  27933. * @method Phaser.Color.getColorInfo
  27934. * @static
  27935. * @param {number} color - A color value in the format 0xAARRGGBB.
  27936. * @returns {string} String containing the 3 lines of information.
  27937. */
  27938. getColorInfo: function (color) {
  27939. var argb = Phaser.Color.getRGB(color);
  27940. var hsl = Phaser.Color.RGBtoHSV(color);
  27941. // Hex format
  27942. var result = Phaser.Color.RGBtoHexstring(color) + "\n";
  27943. // RGB format
  27944. result = result.concat("Alpha: " + argb.alpha + " Red: " + argb.red + " Green: " + argb.green + " Blue: " + argb.blue) + "\n";
  27945. // HSL info
  27946. result = result.concat("Hue: " + hsl.hue + " Saturation: " + hsl.saturation + " Lightnes: " + hsl.lightness);
  27947. return result;
  27948. },
  27949. /**
  27950. * Return a string representation of the color in the format 0xAARRGGBB.
  27951. *
  27952. * @method Phaser.Color.RGBtoHexstring
  27953. * @static
  27954. * @param {number} color - The color to get the string representation for
  27955. * @returns {string} A string of length 10 characters in the format 0xAARRGGBB
  27956. */
  27957. RGBtoHexstring: function (color) {
  27958. var argb = Phaser.Color.getRGB(color);
  27959. return "0x" + Phaser.Color.colorToHexstring(argb.alpha) + Phaser.Color.colorToHexstring(argb.red) + Phaser.Color.colorToHexstring(argb.green) + Phaser.Color.colorToHexstring(argb.blue);
  27960. },
  27961. /**
  27962. * Return a string representation of the color in the format #RRGGBB.
  27963. *
  27964. * @method Phaser.Color.RGBtoWebstring
  27965. * @static
  27966. * @param {number} color - The color to get the string representation for.
  27967. * @returns {string} A string of length 10 characters in the format 0xAARRGGBB.
  27968. */
  27969. RGBtoWebstring: function (color) {
  27970. var argb = Phaser.Color.getRGB(color);
  27971. return "#" + Phaser.Color.colorToHexstring(argb.red) + Phaser.Color.colorToHexstring(argb.green) + Phaser.Color.colorToHexstring(argb.blue);
  27972. },
  27973. /**
  27974. * Return a string containing a hex representation of the given color.
  27975. *
  27976. * @method Phaser.Color.colorToHexstring
  27977. * @static
  27978. * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255).
  27979. * @returns {string} A string of length 2 characters, i.e. 255 = FF, 0 = 00.
  27980. */
  27981. colorToHexstring: function (color) {
  27982. var digits = "0123456789ABCDEF";
  27983. var lsd = color % 16;
  27984. var msd = (color - lsd) / 16;
  27985. var hexified = digits.charAt(msd) + digits.charAt(lsd);
  27986. return hexified;
  27987. },
  27988. /**
  27989. * Interpolates the two given colours based on the supplied step and currentStep properties.
  27990. * @method Phaser.Color.interpolateColor
  27991. * @static
  27992. * @param {number} color1 - The first color value.
  27993. * @param {number} color2 - The second color value.
  27994. * @param {number} steps - The number of steps to run the interpolation over.
  27995. * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
  27996. * @param {number} alpha - The alpha of the returned color.
  27997. * @returns {number} The interpolated color value.
  27998. */
  27999. interpolateColor: function (color1, color2, steps, currentStep, alpha) {
  28000. if (typeof alpha === "undefined") { alpha = 255; }
  28001. var src1 = Phaser.Color.getRGB(color1);
  28002. var src2 = Phaser.Color.getRGB(color2);
  28003. var r = (((src2.red - src1.red) * currentStep) / steps) + src1.red;
  28004. var g = (((src2.green - src1.green) * currentStep) / steps) + src1.green;
  28005. var b = (((src2.blue - src1.blue) * currentStep) / steps) + src1.blue;
  28006. return Phaser.Color.getColor32(alpha, r, g, b);
  28007. },
  28008. /**
  28009. * Interpolates the two given colours based on the supplied step and currentStep properties.
  28010. * @method Phaser.Color.interpolateColorWithRGB
  28011. * @static
  28012. * @param {number} color - The first color value.
  28013. * @param {number} r - The red color value, between 0 and 0xFF (255).
  28014. * @param {number} g - The green color value, between 0 and 0xFF (255).
  28015. * @param {number} b - The blue color value, between 0 and 0xFF (255).
  28016. * @param {number} steps - The number of steps to run the interpolation over.
  28017. * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
  28018. * @returns {number} The interpolated color value.
  28019. */
  28020. interpolateColorWithRGB: function (color, r, g, b, steps, currentStep) {
  28021. var src = Phaser.Color.getRGB(color);
  28022. var or = (((r - src.red) * currentStep) / steps) + src.red;
  28023. var og = (((g - src.green) * currentStep) / steps) + src.green;
  28024. var ob = (((b - src.blue) * currentStep) / steps) + src.blue;
  28025. return Phaser.Color.getColor(or, og, ob);
  28026. },
  28027. /**
  28028. * Interpolates the two given colours based on the supplied step and currentStep properties.
  28029. * @method Phaser.Color.interpolateRGB
  28030. * @static
  28031. * @param {number} r1 - The red color value, between 0 and 0xFF (255).
  28032. * @param {number} g1 - The green color value, between 0 and 0xFF (255).
  28033. * @param {number} b1 - The blue color value, between 0 and 0xFF (255).
  28034. * @param {number} r2 - The red color value, between 0 and 0xFF (255).
  28035. * @param {number} g2 - The green color value, between 0 and 0xFF (255).
  28036. * @param {number} b2 - The blue color value, between 0 and 0xFF (255).
  28037. * @param {number} steps - The number of steps to run the interpolation over.
  28038. * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
  28039. * @returns {number} The interpolated color value.
  28040. */
  28041. interpolateRGB: function (r1, g1, b1, r2, g2, b2, steps, currentStep) {
  28042. var r = (((r2 - r1) * currentStep) / steps) + r1;
  28043. var g = (((g2 - g1) * currentStep) / steps) + g1;
  28044. var b = (((b2 - b1) * currentStep) / steps) + b1;
  28045. return Phaser.Color.getColor(r, g, b);
  28046. },
  28047. /**
  28048. * Returns a random color value between black and white
  28049. * Set the min value to start each channel from the given offset.
  28050. * Set the max value to restrict the maximum color used per channel.
  28051. *
  28052. * @method Phaser.Color.getRandomColor
  28053. * @static
  28054. * @param {number} min - The lowest value to use for the color.
  28055. * @param {number} max - The highest value to use for the color.
  28056. * @param {number} alpha - The alpha value of the returning color (default 255 = fully opaque).
  28057. * @returns {number} 32-bit color value with alpha.
  28058. */
  28059. getRandomColor: function (min, max, alpha) {
  28060. if (typeof min === "undefined") { min = 0; }
  28061. if (typeof max === "undefined") { max = 255; }
  28062. if (typeof alpha === "undefined") { alpha = 255; }
  28063. // Sanity checks
  28064. if (max > 255) {
  28065. return Phaser.Color.getColor(255, 255, 255);
  28066. }
  28067. if (min > max) {
  28068. return Phaser.Color.getColor(255, 255, 255);
  28069. }
  28070. var red = min + Math.round(Math.random() * (max - min));
  28071. var green = min + Math.round(Math.random() * (max - min));
  28072. var blue = min + Math.round(Math.random() * (max - min));
  28073. return Phaser.Color.getColor32(alpha, red, green, blue);
  28074. },
  28075. /**
  28076. * Return the component parts of a color as an Object with the properties alpha, red, green, blue
  28077. *
  28078. * Alpha will only be set if it exist in the given color (0xAARRGGBB)
  28079. *
  28080. * @method Phaser.Color.getRGB
  28081. * @static
  28082. * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB).
  28083. * @returns {object} An Object with properties: alpha, red, green, blue.
  28084. */
  28085. getRGB: function (color) {
  28086. return {
  28087. alpha: color >>> 24,
  28088. red: color >> 16 & 0xFF,
  28089. green: color >> 8 & 0xFF,
  28090. blue: color & 0xFF
  28091. };
  28092. },
  28093. /**
  28094. * Returns a CSS friendly string value from the given color.
  28095. * @method Phaser.Color.getWebRGB
  28096. * @static
  28097. * @param {number} color
  28098. * @returns {string}A string in the format: 'rgba(r,g,b,a)'
  28099. */
  28100. getWebRGB: function (color) {
  28101. var alpha = (color >>> 24) / 255;
  28102. var red = color >> 16 & 0xFF;
  28103. var green = color >> 8 & 0xFF;
  28104. var blue = color & 0xFF;
  28105. return 'rgba(' + red.toString() + ',' + green.toString() + ',' + blue.toString() + ',' + alpha.toString() + ')';
  28106. },
  28107. /**
  28108. * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255.
  28109. *
  28110. * @method Phaser.Color.getAlpha
  28111. * @static
  28112. * @param {number} color - In the format 0xAARRGGBB.
  28113. * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
  28114. */
  28115. getAlpha: function (color) {
  28116. return color >>> 24;
  28117. },
  28118. /**
  28119. * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1.
  28120. *
  28121. * @method Phaser.Color.getAlphaFloat
  28122. * @static
  28123. * @param {number} color - In the format 0xAARRGGBB.
  28124. * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
  28125. */
  28126. getAlphaFloat: function (color) {
  28127. return (color >>> 24) / 255;
  28128. },
  28129. /**
  28130. * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255.
  28131. *
  28132. * @method Phaser.Color.getRed
  28133. * @static
  28134. * @param {number} color In the format 0xAARRGGBB.
  28135. * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red).
  28136. */
  28137. getRed: function (color) {
  28138. return color >> 16 & 0xFF;
  28139. },
  28140. /**
  28141. * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255.
  28142. *
  28143. * @method Phaser.Color.getGreen
  28144. * @static
  28145. * @param {number} color - In the format 0xAARRGGBB.
  28146. * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green).
  28147. */
  28148. getGreen: function (color) {
  28149. return color >> 8 & 0xFF;
  28150. },
  28151. /**
  28152. * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255.
  28153. *
  28154. * @method Phaser.Color.getBlue
  28155. * @static
  28156. * @param {number} color - In the format 0xAARRGGBB.
  28157. * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue).
  28158. */
  28159. getBlue: function (color) {
  28160. return color & 0xFF;
  28161. }
  28162. };
  28163. /**
  28164. * @author Richard Davey <rich@photonstorm.com>
  28165. * @copyright 2013 Photon Storm Ltd.
  28166. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  28167. */
  28168. /**
  28169. * @class Phaser.Physics
  28170. */
  28171. Phaser.Physics = {};
  28172. /**
  28173. * Arcade Physics constructor.
  28174. *
  28175. * @class Phaser.Physics.Arcade
  28176. * @classdesc Arcade Physics Constructor
  28177. * @constructor
  28178. * @param {Phaser.Game} game reference to the current game instance.
  28179. */
  28180. Phaser.Physics.Arcade = function (game) {
  28181. /**
  28182. * @property {Phaser.Game} game - Local reference to game.
  28183. */
  28184. this.game = game;
  28185. /**
  28186. * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity.
  28187. */
  28188. this.gravity = new Phaser.Point();
  28189. /**
  28190. * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds.
  28191. */
  28192. this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height);
  28193. /**
  28194. * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad.
  28195. */
  28196. this.maxObjects = 10;
  28197. /**
  28198. * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels.
  28199. */
  28200. this.maxLevels = 4;
  28201. /**
  28202. * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks.
  28203. */
  28204. this.OVERLAP_BIAS = 4;
  28205. /**
  28206. * @property {Phaser.QuadTree} quadTree - The world QuadTree.
  28207. */
  28208. this.quadTree = new Phaser.QuadTree(this, this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
  28209. /**
  28210. * @property {number} quadTreeID - The QuadTree ID.
  28211. */
  28212. this.quadTreeID = 0;
  28213. // Avoid gc spikes by caching these values for re-use
  28214. /**
  28215. * @property {Phaser.Rectangle} _bounds1 - Internal cache var.
  28216. * @private
  28217. */
  28218. this._bounds1 = new Phaser.Rectangle();
  28219. /**
  28220. * @property {Phaser.Rectangle} _bounds2 - Internal cache var.
  28221. * @private
  28222. */
  28223. this._bounds2 = new Phaser.Rectangle();
  28224. /**
  28225. * @property {number} _overlap - Internal cache var.
  28226. * @private
  28227. */
  28228. this._overlap = 0;
  28229. /**
  28230. * @property {number} _maxOverlap - Internal cache var.
  28231. * @private
  28232. */
  28233. this._maxOverlap = 0;
  28234. /**
  28235. * @property {number} _velocity1 - Internal cache var.
  28236. * @private
  28237. */
  28238. this._velocity1 = 0;
  28239. /**
  28240. * @property {number} _velocity2 - Internal cache var.
  28241. * @private
  28242. */
  28243. this._velocity2 = 0;
  28244. /**
  28245. * @property {number} _newVelocity1 - Internal cache var.
  28246. * @private
  28247. */
  28248. this._newVelocity1 = 0;
  28249. /**
  28250. * @property {number} _newVelocity2 - Internal cache var.
  28251. * @private
  28252. */
  28253. this._newVelocity2 = 0;
  28254. /**
  28255. * @property {number} _average - Internal cache var.
  28256. * @private
  28257. */
  28258. this._average = 0;
  28259. /**
  28260. * @property {Array} _mapData - Internal cache var.
  28261. * @private
  28262. */
  28263. this._mapData = [];
  28264. /**
  28265. * @property {number} _mapTiles - Internal cache var.
  28266. * @private
  28267. */
  28268. this._mapTiles = 0;
  28269. /**
  28270. * @property {boolean} _result - Internal cache var.
  28271. * @private
  28272. */
  28273. this._result = false;
  28274. /**
  28275. * @property {number} _total - Internal cache var.
  28276. * @private
  28277. */
  28278. this._total = 0;
  28279. /**
  28280. * @property {number} _angle - Internal cache var.
  28281. * @private
  28282. */
  28283. this._angle = 0;
  28284. /**
  28285. * @property {number} _dx - Internal cache var.
  28286. * @private
  28287. */
  28288. this._dx = 0;
  28289. /**
  28290. * @property {number} _dy - Internal cache var.
  28291. * @private
  28292. */
  28293. this._dy = 0;
  28294. };
  28295. Phaser.Physics.Arcade.prototype = {
  28296. /**
  28297. * Called automatically by a Physics body, it updates all motion related values on the Body.
  28298. *
  28299. * @method Phaser.Physics.Arcade#updateMotion
  28300. * @param {Phaser.Physics.Arcade.Body} The Body object to be updated.
  28301. */
  28302. updateMotion: function (body) {
  28303. // If you're wondering why the velocity is halved and applied twice, read this: http://www.niksula.hut.fi/~hkankaan/Homepages/gravity.html
  28304. // Rotation
  28305. this._velocityDelta = (this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity) * this.game.time.physicsElapsed * 0.5 * 60;
  28306. body.angularVelocity += this._velocityDelta;
  28307. body.rotation += (body.angularVelocity * this.game.time.physicsElapsed);
  28308. body.angularVelocity += this._velocityDelta;
  28309. // Horizontal
  28310. this._velocityDelta = (this.computeVelocity(1, body, body.velocity.x, body.acceleration.x, body.drag.x, body.maxVelocity.x) - body.velocity.x) * this.game.time.physicsElapsed * 0.5 * 60;
  28311. body.velocity.x += this._velocityDelta;
  28312. body.x += (body.velocity.x * this.game.time.physicsElapsed);
  28313. body.velocity.x += this._velocityDelta;
  28314. // Vertical
  28315. this._velocityDelta = (this.computeVelocity(2, body, body.velocity.y, body.acceleration.y, body.drag.y, body.maxVelocity.y) - body.velocity.y) * this.game.time.physicsElapsed * 0.5 * 60;
  28316. body.velocity.y += this._velocityDelta;
  28317. body.y += (body.velocity.y * this.game.time.physicsElapsed);
  28318. body.velocity.y += this._velocityDelta;
  28319. },
  28320. /**
  28321. * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity.
  28322. *
  28323. * @method Phaser.Physics.Arcade#computeVelocity
  28324. * @param {number} axis - 1 for horizontal, 2 for vertical.
  28325. * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated.
  28326. * @param {number} velocity - Any component of velocity (e.g. 20).
  28327. * @param {number} acceleration - Rate at which the velocity is changing.
  28328. * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set.
  28329. * @param {number} mMax - An absolute value cap for the velocity.
  28330. * @return {number} The altered Velocity value.
  28331. */
  28332. computeVelocity: function (axis, body, velocity, acceleration, drag, max) {
  28333. max = max || 10000;
  28334. if (axis == 1 && body.allowGravity)
  28335. {
  28336. velocity += this.gravity.x + body.gravity.x;
  28337. }
  28338. else if (axis == 2 && body.allowGravity)
  28339. {
  28340. velocity += this.gravity.y + body.gravity.y;
  28341. }
  28342. if (acceleration !== 0)
  28343. {
  28344. velocity += acceleration * this.game.time.physicsElapsed;
  28345. }
  28346. else if (drag !== 0)
  28347. {
  28348. this._drag = drag * this.game.time.physicsElapsed;
  28349. if (velocity - this._drag > 0)
  28350. {
  28351. velocity -= this._drag;
  28352. }
  28353. else if (velocity + this._drag < 0)
  28354. {
  28355. velocity += this._drag;
  28356. }
  28357. else
  28358. {
  28359. velocity = 0;
  28360. }
  28361. }
  28362. if (velocity > max)
  28363. {
  28364. velocity = max;
  28365. }
  28366. else if (velocity < -max)
  28367. {
  28368. velocity = -max;
  28369. }
  28370. return velocity;
  28371. },
  28372. /**
  28373. * Called automatically by the core game loop.
  28374. *
  28375. * @method Phaser.Physics.Arcade#preUpdate
  28376. * @protected
  28377. */
  28378. preUpdate: function () {
  28379. // Clear the tree
  28380. this.quadTree.clear();
  28381. // Create our tree which all of the Physics bodies will add themselves to
  28382. this.quadTreeID = 0;
  28383. this.quadTree = new Phaser.QuadTree(this, this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
  28384. },
  28385. /**
  28386. * Called automatically by the core game loop.
  28387. *
  28388. * @method Phaser.Physics.Arcade#postUpdate
  28389. * @protected
  28390. */
  28391. postUpdate: function () {
  28392. // Clear the tree ready for the next update
  28393. this.quadTree.clear();
  28394. },
  28395. /**
  28396. * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters.
  28397. * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks.
  28398. * Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results.
  28399. *
  28400. * @method Phaser.Physics.Arcade#overlap
  28401. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
  28402. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
  28403. * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them.
  28404. * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then overlapCallback will only be called if processCallback returns true.
  28405. * @param {object} [callbackContext] - The context in which to run the callbacks.
  28406. * @returns {boolean} True if an overlap occured otherwise false.
  28407. */
  28408. overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) {
  28409. overlapCallback = overlapCallback || null;
  28410. processCallback = processCallback || null;
  28411. callbackContext = callbackContext || overlapCallback;
  28412. this._result = false;
  28413. this._total = 0;
  28414. // Only test valid objects
  28415. if (object1 && object2 && object1.exists && object2.exists)
  28416. {
  28417. // SPRITES
  28418. if (object1.type == Phaser.SPRITE)
  28419. {
  28420. if (object2.type == Phaser.SPRITE)
  28421. {
  28422. this.overlapSpriteVsSprite(object1, object2, overlapCallback, processCallback, callbackContext);
  28423. }
  28424. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  28425. {
  28426. this.overlapSpriteVsGroup(object1, object2, overlapCallback, processCallback, callbackContext);
  28427. }
  28428. }
  28429. // GROUPS
  28430. else if (object1.type == Phaser.GROUP)
  28431. {
  28432. if (object2.type == Phaser.SPRITE)
  28433. {
  28434. this.overlapSpriteVsGroup(object2, object1, overlapCallback, processCallback, callbackContext);
  28435. }
  28436. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  28437. {
  28438. this.overlapGroupVsGroup(object1, object2, overlapCallback, processCallback, callbackContext);
  28439. }
  28440. }
  28441. // EMITTER
  28442. else if (object1.type == Phaser.EMITTER)
  28443. {
  28444. if (object2.type == Phaser.SPRITE)
  28445. {
  28446. this.overlapSpriteVsGroup(object2, object1, overlapCallback, processCallback, callbackContext);
  28447. }
  28448. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  28449. {
  28450. this.overlapGroupVsGroup(object1, object2, overlapCallback, processCallback, callbackContext);
  28451. }
  28452. }
  28453. }
  28454. return (this._total > 0);
  28455. },
  28456. /**
  28457. * An internal function. Use Phaser.Physics.Arcade.overlap instead.
  28458. *
  28459. * @method Phaser.Physics.Arcade#overlapSpriteVsSprite
  28460. * @private
  28461. */
  28462. overlapSpriteVsSprite: function (sprite1, sprite2, overlapCallback, processCallback, callbackContext) {
  28463. this._result = Phaser.Rectangle.intersects(sprite1.body, sprite2.body);
  28464. if (this._result)
  28465. {
  28466. // They collided, is there a custom process callback?
  28467. if (processCallback)
  28468. {
  28469. if (processCallback.call(callbackContext, sprite1, sprite2))
  28470. {
  28471. this._total++;
  28472. if (overlapCallback)
  28473. {
  28474. overlapCallback.call(callbackContext, sprite1, sprite2);
  28475. }
  28476. }
  28477. }
  28478. else
  28479. {
  28480. this._total++;
  28481. if (overlapCallback)
  28482. {
  28483. overlapCallback.call(callbackContext, sprite1, sprite2);
  28484. }
  28485. }
  28486. }
  28487. },
  28488. /**
  28489. * An internal function. Use Phaser.Physics.Arcade.overlap instead.
  28490. *
  28491. * @method Phaser.Physics.Arcade#overlapSpriteVsGroup
  28492. * @private
  28493. */
  28494. overlapSpriteVsGroup: function (sprite, group, overlapCallback, processCallback, callbackContext) {
  28495. if (group.length === 0)
  28496. {
  28497. return;
  28498. }
  28499. // What is the sprite colliding with in the quadtree?
  28500. this._potentials = this.quadTree.retrieve(sprite);
  28501. for (var i = 0, len = this._potentials.length; i < len; i++)
  28502. {
  28503. // We have our potential suspects, are they in this group?
  28504. if (this._potentials[i].sprite.group == group)
  28505. {
  28506. this._result = Phaser.Rectangle.intersects(sprite.body, this._potentials[i]);
  28507. if (this._result && processCallback)
  28508. {
  28509. this._result = processCallback.call(callbackContext, sprite, this._potentials[i].sprite);
  28510. }
  28511. if (this._result)
  28512. {
  28513. this._total++;
  28514. if (overlapCallback)
  28515. {
  28516. overlapCallback.call(callbackContext, sprite, this._potentials[i].sprite);
  28517. }
  28518. }
  28519. }
  28520. }
  28521. },
  28522. /**
  28523. * An internal function. Use Phaser.Physics.Arcade.overlap instead.
  28524. *
  28525. * @method Phaser.Physics.Arcade#overlapGroupVsGroup
  28526. * @private
  28527. */
  28528. overlapGroupVsGroup: function (group1, group2, overlapCallback, processCallback, callbackContext) {
  28529. if (group1.length === 0 || group2.length === 0)
  28530. {
  28531. return;
  28532. }
  28533. if (group1._container.first._iNext)
  28534. {
  28535. var currentNode = group1._container.first._iNext;
  28536. do
  28537. {
  28538. if (currentNode.exists)
  28539. {
  28540. this.overlapSpriteVsGroup(currentNode, group2, overlapCallback, processCallback, callbackContext);
  28541. }
  28542. currentNode = currentNode._iNext;
  28543. }
  28544. while (currentNode != group1._container.last._iNext);
  28545. }
  28546. },
  28547. /**
  28548. * Checks for collision between two game objects. The objects can be Sprites, Groups, Emitters or Tilemap Layers.
  28549. * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions.
  28550. * The objects are also automatically separated.
  28551. *
  28552. * @method Phaser.Physics.Arcade#collide
  28553. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.Tilemap
  28554. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.Tilemap
  28555. * @param {function} [collideCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them.
  28556. * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collideCallback will only be called if processCallback returns true.
  28557. * @param {object} [callbackContext] - The context in which to run the callbacks.
  28558. * @returns {boolean} True if a collision occured otherwise false.
  28559. */
  28560. collide: function (object1, object2, collideCallback, processCallback, callbackContext) {
  28561. collideCallback = collideCallback || null;
  28562. processCallback = processCallback || null;
  28563. callbackContext = callbackContext || collideCallback;
  28564. this._result = false;
  28565. this._total = 0;
  28566. // Only collide valid objects
  28567. if (object1 && object2 && object1.exists && object2.exists)
  28568. {
  28569. // Can expand to support Buttons, Text, etc at a later date. For now these are the essentials.
  28570. // SPRITES
  28571. if (object1.type == Phaser.SPRITE)
  28572. {
  28573. if (object2.type == Phaser.SPRITE)
  28574. {
  28575. this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext);
  28576. }
  28577. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  28578. {
  28579. this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext);
  28580. }
  28581. else if (object2.type == Phaser.TILEMAPLAYER)
  28582. {
  28583. this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
  28584. }
  28585. }
  28586. // GROUPS
  28587. else if (object1.type == Phaser.GROUP)
  28588. {
  28589. if (object2.type == Phaser.SPRITE)
  28590. {
  28591. this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext);
  28592. }
  28593. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  28594. {
  28595. this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext);
  28596. }
  28597. else if (object2.type == Phaser.TILEMAPLAYER)
  28598. {
  28599. this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
  28600. }
  28601. }
  28602. // TILEMAP LAYERS
  28603. else if (object1.type == Phaser.TILEMAPLAYER)
  28604. {
  28605. if (object2.type == Phaser.SPRITE)
  28606. {
  28607. this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
  28608. }
  28609. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  28610. {
  28611. this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
  28612. }
  28613. }
  28614. // EMITTER
  28615. else if (object1.type == Phaser.EMITTER)
  28616. {
  28617. if (object2.type == Phaser.SPRITE)
  28618. {
  28619. this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext);
  28620. }
  28621. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  28622. {
  28623. this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext);
  28624. }
  28625. else if (object2.type == Phaser.TILEMAPLAYER)
  28626. {
  28627. this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
  28628. }
  28629. }
  28630. }
  28631. return (this._total > 0);
  28632. },
  28633. /**
  28634. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  28635. *
  28636. * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer
  28637. * @private
  28638. */
  28639. collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext) {
  28640. this._mapData = tilemapLayer.getTiles(sprite.body.x, sprite.body.y, sprite.body.width, sprite.body.height, true);
  28641. if (this._mapData.length === 0)
  28642. {
  28643. return;
  28644. }
  28645. for (var i = 0; i < this._mapData.length; i++)
  28646. {
  28647. if (this.separateTile(sprite.body, this._mapData[i]))
  28648. {
  28649. // They collided, is there a custom process callback?
  28650. if (processCallback)
  28651. {
  28652. if (processCallback.call(callbackContext, sprite, this._mapData[i]))
  28653. {
  28654. this._total++;
  28655. if (collideCallback)
  28656. {
  28657. collideCallback.call(callbackContext, sprite, this._mapData[i]);
  28658. }
  28659. }
  28660. }
  28661. else
  28662. {
  28663. this._total++;
  28664. if (collideCallback)
  28665. {
  28666. collideCallback.call(callbackContext, sprite, this._mapData[i]);
  28667. }
  28668. }
  28669. }
  28670. }
  28671. },
  28672. /**
  28673. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  28674. *
  28675. * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer
  28676. * @private
  28677. */
  28678. collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext) {
  28679. if (group.length === 0)
  28680. {
  28681. return;
  28682. }
  28683. if (group.length === 0)
  28684. {
  28685. return;
  28686. }
  28687. if (group._container.first._iNext)
  28688. {
  28689. var currentNode = group._container.first._iNext;
  28690. do
  28691. {
  28692. if (currentNode.exists)
  28693. {
  28694. this.collideSpriteVsTilemapLayer(currentNode, tilemapLayer, collideCallback, processCallback, callbackContext);
  28695. }
  28696. currentNode = currentNode._iNext;
  28697. }
  28698. while (currentNode != group._container.last._iNext);
  28699. }
  28700. },
  28701. /**
  28702. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  28703. *
  28704. * @method Phaser.Physics.Arcade#collideSpriteVsSprite
  28705. * @private
  28706. */
  28707. collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext) {
  28708. this.separate(sprite1.body, sprite2.body);
  28709. if (this._result)
  28710. {
  28711. // They collided, is there a custom process callback?
  28712. if (processCallback)
  28713. {
  28714. if (processCallback.call(callbackContext, sprite1, sprite2))
  28715. {
  28716. this._total++;
  28717. if (collideCallback)
  28718. {
  28719. collideCallback.call(callbackContext, sprite1, sprite2);
  28720. }
  28721. }
  28722. }
  28723. else
  28724. {
  28725. this._total++;
  28726. if (collideCallback)
  28727. {
  28728. collideCallback.call(callbackContext, sprite1, sprite2);
  28729. }
  28730. }
  28731. }
  28732. },
  28733. /**
  28734. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  28735. *
  28736. * @method Phaser.Physics.Arcade#collideSpriteVsGroup
  28737. * @private
  28738. */
  28739. collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext) {
  28740. if (group.length === 0)
  28741. {
  28742. return;
  28743. }
  28744. // What is the sprite colliding with in the quadtree?
  28745. this._potentials = this.quadTree.retrieve(sprite);
  28746. for (var i = 0, len = this._potentials.length; i < len; i++)
  28747. {
  28748. // We have our potential suspects, are they in this group?
  28749. if (this._potentials[i].sprite.group == group)
  28750. {
  28751. this.separate(sprite.body, this._potentials[i]);
  28752. if (this._result && processCallback)
  28753. {
  28754. this._result = processCallback.call(callbackContext, sprite, this._potentials[i].sprite);
  28755. }
  28756. if (this._result)
  28757. {
  28758. this._total++;
  28759. if (collideCallback)
  28760. {
  28761. collideCallback.call(callbackContext, sprite, this._potentials[i].sprite);
  28762. }
  28763. }
  28764. }
  28765. }
  28766. },
  28767. /**
  28768. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  28769. *
  28770. * @method Phaser.Physics.Arcade#collideGroupVsGroup
  28771. * @private
  28772. */
  28773. collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext) {
  28774. if (group1.length === 0 || group2.length === 0)
  28775. {
  28776. return;
  28777. }
  28778. if (group1._container.first._iNext)
  28779. {
  28780. var currentNode = group1._container.first._iNext;
  28781. do
  28782. {
  28783. if (currentNode.exists)
  28784. {
  28785. this.collideSpriteVsGroup(currentNode, group2, collideCallback, processCallback, callbackContext);
  28786. }
  28787. currentNode = currentNode._iNext;
  28788. }
  28789. while (currentNode != group1._container.last._iNext);
  28790. }
  28791. },
  28792. /**
  28793. * The core separation function to separate two physics bodies.
  28794. * @method Phaser.Physics.Arcade#separate
  28795. * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
  28796. * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
  28797. * @returns {boolean} Returns true if the bodies were separated, otherwise false.
  28798. */
  28799. separate: function (body1, body2) {
  28800. this._result = (this.separateX(body1, body2) || this.separateY(body1, body2));
  28801. },
  28802. /**
  28803. * The core separation function to separate two physics bodies on the x axis.
  28804. * @method Phaser.Physics.Arcade#separateX
  28805. * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
  28806. * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
  28807. * @returns {boolean} Returns true if the bodies were separated, otherwise false.
  28808. */
  28809. separateX: function (body1, body2) {
  28810. // Can't separate two immovable bodies
  28811. if (body1.immovable && body2.immovable)
  28812. {
  28813. return false;
  28814. }
  28815. this._overlap = 0;
  28816. // Check if the hulls actually overlap
  28817. if (Phaser.Rectangle.intersects(body1, body2))
  28818. {
  28819. this._maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS;
  28820. if (body1.deltaX() === 0 && body2.deltaX() === 0)
  28821. {
  28822. // They overlap but neither of them are moving
  28823. body1.embedded = true;
  28824. body2.embedded = true;
  28825. }
  28826. else if (body1.deltaX() > body2.deltaX())
  28827. {
  28828. // Body1 is moving right and/or Body2 is moving left
  28829. this._overlap = body1.x + body1.width - body2.x;
  28830. if ((this._overlap > this._maxOverlap) || body1.allowCollision.right === false || body2.allowCollision.left === false)
  28831. {
  28832. this._overlap = 0;
  28833. }
  28834. else
  28835. {
  28836. body1.touching.right = true;
  28837. body2.touching.left = true;
  28838. }
  28839. }
  28840. else if (body1.deltaX() < body2.deltaX())
  28841. {
  28842. // Body1 is moving left and/or Body2 is moving right
  28843. this._overlap = body1.x - body2.width - body2.x;
  28844. if ((-this._overlap > this._maxOverlap) || body1.allowCollision.left === false || body2.allowCollision.right === false)
  28845. {
  28846. this._overlap = 0;
  28847. }
  28848. else
  28849. {
  28850. body1.touching.left = true;
  28851. body2.touching.right = true;
  28852. }
  28853. }
  28854. // Then adjust their positions and velocities accordingly (if there was any overlap)
  28855. if (this._overlap !== 0)
  28856. {
  28857. body1.overlapX = this._overlap;
  28858. body2.overlapX = this._overlap;
  28859. if (body1.customSeparateX || body2.customSeparateX)
  28860. {
  28861. return true;
  28862. }
  28863. this._velocity1 = body1.velocity.x;
  28864. this._velocity2 = body2.velocity.x;
  28865. if (!body1.immovable && !body2.immovable)
  28866. {
  28867. this._overlap *= 0.5;
  28868. body1.x = body1.x - this._overlap;
  28869. body2.x += this._overlap;
  28870. this._newVelocity1 = Math.sqrt((this._velocity2 * this._velocity2 * body2.mass) / body1.mass) * ((this._velocity2 > 0) ? 1 : -1);
  28871. this._newVelocity2 = Math.sqrt((this._velocity1 * this._velocity1 * body1.mass) / body2.mass) * ((this._velocity1 > 0) ? 1 : -1);
  28872. this._average = (this._newVelocity1 + this._newVelocity2) * 0.5;
  28873. this._newVelocity1 -= this._average;
  28874. this._newVelocity2 -= this._average;
  28875. body1.velocity.x = this._average + this._newVelocity1 * body1.bounce.x;
  28876. body2.velocity.x = this._average + this._newVelocity2 * body2.bounce.x;
  28877. }
  28878. else if (!body1.immovable)
  28879. {
  28880. body1.x = body1.x - this._overlap;
  28881. body1.velocity.x = this._velocity2 - this._velocity1 * body1.bounce.x;
  28882. }
  28883. else if (!body2.immovable)
  28884. {
  28885. body2.x += this._overlap;
  28886. body2.velocity.x = this._velocity1 - this._velocity2 * body2.bounce.x;
  28887. }
  28888. body1.updateHulls();
  28889. body2.updateHulls();
  28890. return true;
  28891. }
  28892. }
  28893. return false;
  28894. },
  28895. /**
  28896. * The core separation function to separate two physics bodies on the y axis.
  28897. * @method Phaser.Physics.Arcade#separateY
  28898. * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
  28899. * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
  28900. * @returns {boolean} Returns true if the bodies were separated, otherwise false.
  28901. */
  28902. separateY: function (body1, body2) {
  28903. // Can't separate two immovable or non-existing bodys
  28904. if (body1.immovable && body2.immovable)
  28905. {
  28906. return false;
  28907. }
  28908. this._overlap = 0;
  28909. // Check if the hulls actually overlap
  28910. if (Phaser.Rectangle.intersects(body1, body2))
  28911. {
  28912. this._maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS;
  28913. if (body1.deltaY() === 0 && body2.deltaY() === 0)
  28914. {
  28915. // They overlap but neither of them are moving
  28916. body1.embedded = true;
  28917. body2.embedded = true;
  28918. }
  28919. else if (body1.deltaY() > body2.deltaY())
  28920. {
  28921. // Body1 is moving down and/or Body2 is moving up
  28922. this._overlap = body1.y + body1.height - body2.y;
  28923. if ((this._overlap > this._maxOverlap) || body1.allowCollision.down === false || body2.allowCollision.up === false)
  28924. {
  28925. this._overlap = 0;
  28926. }
  28927. else
  28928. {
  28929. body1.touching.down = true;
  28930. body2.touching.up = true;
  28931. }
  28932. }
  28933. else if (body1.deltaY() < body2.deltaY())
  28934. {
  28935. // Body1 is moving up and/or Body2 is moving down
  28936. this._overlap = body1.y - body2.height - body2.y;
  28937. if ((-this._overlap > this._maxOverlap) || body1.allowCollision.up === false || body2.allowCollision.down === false)
  28938. {
  28939. this._overlap = 0;
  28940. }
  28941. else
  28942. {
  28943. body1.touching.up = true;
  28944. body2.touching.down = true;
  28945. }
  28946. }
  28947. // Then adjust their positions and velocities accordingly (if there was any overlap)
  28948. if (this._overlap !== 0)
  28949. {
  28950. body1.overlapY = this._overlap;
  28951. body2.overlapY = this._overlap;
  28952. if (body1.customSeparateY || body2.customSeparateY)
  28953. {
  28954. return true;
  28955. }
  28956. this._velocity1 = body1.velocity.y;
  28957. this._velocity2 = body2.velocity.y;
  28958. if (!body1.immovable && !body2.immovable)
  28959. {
  28960. this._overlap *= 0.5;
  28961. body1.y = body1.y - this._overlap;
  28962. body2.y += this._overlap;
  28963. this._newVelocity1 = Math.sqrt((this._velocity2 * this._velocity2 * body2.mass) / body1.mass) * ((this._velocity2 > 0) ? 1 : -1);
  28964. this._newVelocity2 = Math.sqrt((this._velocity1 * this._velocity1 * body1.mass) / body2.mass) * ((this._velocity1 > 0) ? 1 : -1);
  28965. this._average = (this._newVelocity1 + this._newVelocity2) * 0.5;
  28966. this._newVelocity1 -= this._average;
  28967. this._newVelocity2 -= this._average;
  28968. body1.velocity.y = this._average + this._newVelocity1 * body1.bounce.y;
  28969. body2.velocity.y = this._average + this._newVelocity2 * body2.bounce.y;
  28970. }
  28971. else if (!body1.immovable)
  28972. {
  28973. body1.y = body1.y - this._overlap;
  28974. body1.velocity.y = this._velocity2 - this._velocity1 * body1.bounce.y;
  28975. // This is special case code that handles things like horizontal moving platforms you can ride
  28976. if (body2.active && body2.moves && (body1.deltaY() > body2.deltaY()))
  28977. {
  28978. body1.x += body2.x - body2.lastX;
  28979. }
  28980. }
  28981. else if (!body2.immovable)
  28982. {
  28983. body2.y += this._overlap;
  28984. body2.velocity.y = this._velocity1 - this._velocity2 * body2.bounce.y;
  28985. // This is special case code that handles things like horizontal moving platforms you can ride
  28986. if (body1.sprite.active && body1.moves && (body1.deltaY() < body2.deltaY()))
  28987. {
  28988. body2.x += body1.x - body1.lastX;
  28989. }
  28990. }
  28991. body1.updateHulls();
  28992. body2.updateHulls();
  28993. return true;
  28994. }
  28995. }
  28996. return false;
  28997. },
  28998. /**
  28999. * The core separation function to separate a physics body and a tile.
  29000. * @method Phaser.Physics.Arcade#separateTile
  29001. * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
  29002. * @param {Phaser.Tile} tile - The tile to collide against.
  29003. * @returns {boolean} Returns true if the bodies were separated, otherwise false.
  29004. */
  29005. separateTile: function (body, tile) {
  29006. this._result = (this.separateTileX(body, tile, true) || this.separateTileY(body, tile, true));
  29007. return this._result;
  29008. },
  29009. /**
  29010. * The core separation function to separate a physics body and a tile on the x axis.
  29011. * @method Phaser.Physics.Arcade#separateTileX
  29012. * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
  29013. * @param {Phaser.Tile} tile - The tile to collide against.
  29014. * @returns {boolean} Returns true if the bodies were separated, otherwise false.
  29015. */
  29016. separateTileX: function (body, tile, separate) {
  29017. // Can't separate two immovable objects (tiles are always immovable)
  29018. if (body.immovable || body.deltaX() === 0 || Phaser.Rectangle.intersects(body.hullX, tile) === false)
  29019. {
  29020. return false;
  29021. }
  29022. this._overlap = 0;
  29023. // The hulls overlap, let's process it
  29024. // this._maxOverlap = body.deltaAbsX() + this.OVERLAP_BIAS;
  29025. if (body.deltaX() < 0)
  29026. {
  29027. // Moving left
  29028. this._overlap = tile.right - body.hullX.x;
  29029. // if ((this._overlap > this._maxOverlap) || body.allowCollision.left === false || tile.tile.collideRight === false)
  29030. if (body.allowCollision.left === false || tile.tile.collideRight === false)
  29031. {
  29032. this._overlap = 0;
  29033. }
  29034. else
  29035. {
  29036. body.touching.left = true;
  29037. }
  29038. }
  29039. else
  29040. {
  29041. // Moving right
  29042. this._overlap = body.hullX.right - tile.x;
  29043. // if ((this._overlap > this._maxOverlap) || body.allowCollision.right === false || tile.tile.collideLeft === false)
  29044. if (body.allowCollision.right === false || tile.tile.collideLeft === false)
  29045. {
  29046. this._overlap = 0;
  29047. }
  29048. else
  29049. {
  29050. body.touching.right = true;
  29051. }
  29052. }
  29053. // Then adjust their positions and velocities accordingly (if there was any overlap)
  29054. if (this._overlap !== 0)
  29055. {
  29056. if (separate)
  29057. {
  29058. if (body.deltaX() < 0)
  29059. {
  29060. body.x = body.x + this._overlap;
  29061. }
  29062. else
  29063. {
  29064. body.x = body.x - this._overlap;
  29065. }
  29066. if (body.bounce.x === 0)
  29067. {
  29068. body.velocity.x = 0;
  29069. }
  29070. else
  29071. {
  29072. body.velocity.x = -body.velocity.x * body.bounce.x;
  29073. }
  29074. body.updateHulls();
  29075. }
  29076. return true;
  29077. }
  29078. else
  29079. {
  29080. return false;
  29081. }
  29082. },
  29083. /**
  29084. * The core separation function to separate a physics body and a tile on the x axis.
  29085. * @method Phaser.Physics.Arcade#separateTileY
  29086. * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
  29087. * @param {Phaser.Tile} tile - The tile to collide against.
  29088. * @returns {boolean} Returns true if the bodies were separated, otherwise false.
  29089. */
  29090. separateTileY: function (body, tile, separate) {
  29091. // Can't separate two immovable objects (tiles are always immovable)
  29092. if (body.immovable || body.deltaY() === 0 || Phaser.Rectangle.intersects(body.hullY, tile) === false)
  29093. {
  29094. return false;
  29095. }
  29096. this._overlap = 0;
  29097. // The hulls overlap, let's process it
  29098. // this._maxOverlap = body.deltaAbsY() + this.OVERLAP_BIAS;
  29099. if (body.deltaY() < 0)
  29100. {
  29101. // Moving up
  29102. this._overlap = tile.bottom - body.hullY.y;
  29103. // if ((this._overlap > this._maxOverlap) || body.allowCollision.up === false || tile.tile.collideDown === false)
  29104. if (body.allowCollision.up === false || tile.tile.collideDown === false)
  29105. {
  29106. this._overlap = 0;
  29107. }
  29108. else
  29109. {
  29110. body.touching.up = true;
  29111. }
  29112. }
  29113. else
  29114. {
  29115. // Moving down
  29116. this._overlap = body.hullY.bottom - tile.y;
  29117. // if ((this._overlap > this._maxOverlap) || body.allowCollision.down === false || tile.tile.collideUp === false)
  29118. if (body.allowCollision.down === false || tile.tile.collideUp === false)
  29119. {
  29120. this._overlap = 0;
  29121. }
  29122. else
  29123. {
  29124. body.touching.down = true;
  29125. }
  29126. }
  29127. // Then adjust their positions and velocities accordingly (if there was any overlap)
  29128. if (this._overlap !== 0)
  29129. {
  29130. if (separate)
  29131. {
  29132. if (body.deltaY() < 0)
  29133. {
  29134. body.y = body.y + this._overlap;
  29135. }
  29136. else
  29137. {
  29138. body.y = body.y - this._overlap;
  29139. }
  29140. if (body.bounce.y === 0)
  29141. {
  29142. body.velocity.y = 0;
  29143. }
  29144. else
  29145. {
  29146. body.velocity.y = -body.velocity.y * body.bounce.y;
  29147. }
  29148. body.updateHulls();
  29149. }
  29150. return true;
  29151. }
  29152. else
  29153. {
  29154. return false;
  29155. }
  29156. },
  29157. /**
  29158. * Move the given display object towards the destination object at a steady velocity.
  29159. * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
  29160. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  29161. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  29162. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  29163. * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
  29164. *
  29165. * @method Phaser.Physics.Arcade#moveToObject
  29166. * @param {any} displayObject - The display object to move.
  29167. * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
  29168. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  29169. * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
  29170. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  29171. */
  29172. moveToObject: function (displayObject, destination, speed, maxTime) {
  29173. if (typeof speed === 'undefined') { speed = 60; }
  29174. if (typeof maxTime === 'undefined') { maxTime = 0; }
  29175. this._angle = Math.atan2(destination.y - displayObject.y, destination.x - displayObject.x);
  29176. if (maxTime > 0)
  29177. {
  29178. // We know how many pixels we need to move, but how fast?
  29179. speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000);
  29180. }
  29181. displayObject.body.velocity.x = Math.cos(this._angle) * speed;
  29182. displayObject.body.velocity.y = Math.sin(this._angle) * speed;
  29183. return this._angle;
  29184. },
  29185. /**
  29186. * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer.
  29187. * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
  29188. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  29189. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  29190. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  29191. *
  29192. * @method Phaser.Physics.Arcade#moveToPointer
  29193. * @param {any} displayObject - The display object to move.
  29194. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  29195. * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
  29196. * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
  29197. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  29198. */
  29199. moveToPointer: function (displayObject, speed, pointer, maxTime) {
  29200. if (typeof speed === 'undefined') { speed = 60; }
  29201. pointer = pointer || this.game.input.activePointer;
  29202. if (typeof maxTime === 'undefined') { maxTime = 0; }
  29203. this._angle = this.angleToPointer(displayObject, pointer);
  29204. if (maxTime > 0)
  29205. {
  29206. // We know how many pixels we need to move, but how fast?
  29207. speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000);
  29208. }
  29209. displayObject.body.velocity.x = Math.cos(this._angle) * speed;
  29210. displayObject.body.velocity.y = Math.sin(this._angle) * speed;
  29211. return this._angle;
  29212. },
  29213. /**
  29214. * Move the given display object towards the x/y coordinates at a steady velocity.
  29215. * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
  29216. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  29217. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  29218. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  29219. * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
  29220. *
  29221. * @method Phaser.Physics.Arcade#moveToXY
  29222. * @param {any} displayObject - The display object to move.
  29223. * @param {number} x - The x coordinate to move towards.
  29224. * @param {number} y - The y coordinate to move towards.
  29225. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  29226. * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
  29227. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  29228. */
  29229. moveToXY: function (displayObject, x, y, speed, maxTime) {
  29230. if (typeof speed === 'undefined') { speed = 60; }
  29231. if (typeof maxTime === 'undefined') { maxTime = 0; }
  29232. this._angle = Math.atan2(y - displayObject.y, x - displayObject.x);
  29233. if (maxTime > 0)
  29234. {
  29235. // We know how many pixels we need to move, but how fast?
  29236. speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000);
  29237. }
  29238. displayObject.body.velocity.x = Math.cos(this._angle) * speed;
  29239. displayObject.body.velocity.y = Math.sin(this._angle) * speed;
  29240. return this._angle;
  29241. },
  29242. /**
  29243. * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object.
  29244. * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
  29245. *
  29246. * @method Phaser.Physics.Arcade#velocityFromAngle
  29247. * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
  29248. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  29249. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
  29250. * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
  29251. */
  29252. velocityFromAngle: function (angle, speed, point) {
  29253. if (typeof speed === 'undefined') { speed = 60; }
  29254. point = point || new Phaser.Point();
  29255. return point.setTo((Math.cos(this.game.math.degToRad(angle)) * speed), (Math.sin(this.game.math.degToRad(angle)) * speed));
  29256. },
  29257. /**
  29258. * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object.
  29259. * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
  29260. *
  29261. * @method Phaser.Physics.Arcade#velocityFromRotation
  29262. * @param {number} rotation - The angle in radians.
  29263. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  29264. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
  29265. * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
  29266. */
  29267. velocityFromRotation: function (rotation, speed, point) {
  29268. if (typeof speed === 'undefined') { speed = 60; }
  29269. point = point || new Phaser.Point();
  29270. return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
  29271. },
  29272. /**
  29273. * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object.
  29274. * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
  29275. *
  29276. * @method Phaser.Physics.Arcade#accelerationFromRotation
  29277. * @param {number} rotation - The angle in radians.
  29278. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  29279. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration.
  29280. * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value.
  29281. */
  29282. accelerationFromRotation: function (rotation, speed, point) {
  29283. if (typeof speed === 'undefined') { speed = 60; }
  29284. point = point || new Phaser.Point();
  29285. return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
  29286. },
  29287. /**
  29288. * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.)
  29289. * You must give a maximum speed value, beyond which the display object won't go any faster.
  29290. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  29291. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  29292. *
  29293. * @method Phaser.Physics.Arcade#accelerateToObject
  29294. * @param {any} displayObject - The display object to move.
  29295. * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
  29296. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  29297. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  29298. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  29299. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  29300. */
  29301. accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) {
  29302. if (typeof speed === 'undefined') { speed = 60; }
  29303. if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; }
  29304. if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; }
  29305. this._angle = this.angleBetween(displayObject, destination);
  29306. displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed);
  29307. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  29308. return this._angle;
  29309. },
  29310. /**
  29311. * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.)
  29312. * You must give a maximum speed value, beyond which the display object won't go any faster.
  29313. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  29314. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  29315. *
  29316. * @method Phaser.Physics.Arcade#accelerateToPointer
  29317. * @param {any} displayObject - The display object to move.
  29318. * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
  29319. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  29320. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  29321. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  29322. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  29323. */
  29324. accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) {
  29325. if (typeof speed === 'undefined') { speed = 60; }
  29326. if (typeof pointer === 'undefined') { pointer = this.game.input.activePointer; }
  29327. if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; }
  29328. if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; }
  29329. this._angle = this.angleToPointer(displayObject, pointer);
  29330. displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed);
  29331. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  29332. return this._angle;
  29333. },
  29334. /**
  29335. * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.)
  29336. * You must give a maximum speed value, beyond which the display object won't go any faster.
  29337. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  29338. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  29339. *
  29340. * @method Phaser.Physics.Arcade#accelerateToXY
  29341. * @param {any} displayObject - The display object to move.
  29342. * @param {number} x - The x coordinate to accelerate towards.
  29343. * @param {number} y - The y coordinate to accelerate towards.
  29344. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  29345. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  29346. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  29347. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  29348. */
  29349. accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) {
  29350. if (typeof speed === 'undefined') { speed = 60; }
  29351. if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; }
  29352. if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; }
  29353. this._angle = this.angleToXY(displayObject, x, y);
  29354. displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed);
  29355. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  29356. return this._angle;
  29357. },
  29358. /**
  29359. * Find the distance between two display objects (like Sprites).
  29360. *
  29361. * @method Phaser.Physics.Arcade#distanceBetween
  29362. * @param {any} source - The Display Object to test from.
  29363. * @param {any} target - The Display Object to test to.
  29364. * @return {number} The distance between the source and target objects.
  29365. */
  29366. distanceBetween: function (source, target) {
  29367. this._dx = source.x - target.x;
  29368. this._dy = source.y - target.y;
  29369. return Math.sqrt(this._dx * this._dx + this._dy * this._dy);
  29370. },
  29371. /**
  29372. * Find the distance between a display object (like a Sprite) and the given x/y coordinates.
  29373. * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
  29374. * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
  29375. *
  29376. * @method Phaser.Physics.Arcade#distanceToXY
  29377. * @param {any} displayObject - The Display Object to test from.
  29378. * @param {number} x - The x coordinate to move towards.
  29379. * @param {number} y - The y coordinate to move towards.
  29380. * @return {number} The distance between the object and the x/y coordinates.
  29381. */
  29382. distanceToXY: function (displayObject, x, y) {
  29383. this._dx = displayObject.x - x;
  29384. this._dy = displayObject.y - y;
  29385. return Math.sqrt(this._dx * this._dx + this._dy * this._dy);
  29386. },
  29387. /**
  29388. * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used.
  29389. * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
  29390. * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
  29391. *
  29392. * @method Phaser.Physics.Arcade#distanceToPointer
  29393. * @param {any} displayObject - The Display Object to test from.
  29394. * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
  29395. * @return {number} The distance between the object and the Pointer.
  29396. */
  29397. distanceToPointer: function (displayObject, pointer) {
  29398. pointer = pointer || this.game.input.activePointer;
  29399. this._dx = displayObject.x - pointer.x;
  29400. this._dy = displayObject.y - pointer.y;
  29401. return Math.sqrt(this._dx * this._dx + this._dy * this._dy);
  29402. },
  29403. /**
  29404. * Find the angle in radians between two display objects (like Sprites).
  29405. *
  29406. * @method Phaser.Physics.Arcade#angleBetween
  29407. * @param {any} source - The Display Object to test from.
  29408. * @param {any} target - The Display Object to test to.
  29409. * @return {number} The angle in radians between the source and target display objects.
  29410. */
  29411. angleBetween: function (source, target) {
  29412. this._dx = target.x - source.x;
  29413. this._dy = target.y - source.y;
  29414. return Math.atan2(this._dy, this._dx);
  29415. },
  29416. /**
  29417. * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate.
  29418. *
  29419. * @method Phaser.Physics.Arcade#angleToXY
  29420. * @param {any} displayObject - The Display Object to test from.
  29421. * @param {number} x - The x coordinate to get the angle to.
  29422. * @param {number} y - The y coordinate to get the angle to.
  29423. * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
  29424. */
  29425. angleToXY: function (displayObject, x, y) {
  29426. this._dx = x - displayObject.x;
  29427. this._dy = y - displayObject.y;
  29428. return Math.atan2(this._dy, this._dx);
  29429. },
  29430. /**
  29431. * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account.
  29432. *
  29433. * @method Phaser.Physics.Arcade#angleToPointer
  29434. * @param {any} displayObject - The Display Object to test from.
  29435. * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
  29436. * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
  29437. */
  29438. angleToPointer: function (displayObject, pointer) {
  29439. pointer = pointer || this.game.input.activePointer;
  29440. this._dx = pointer.worldX - displayObject.x;
  29441. this._dy = pointer.worldY - displayObject.y;
  29442. return Math.atan2(this._dy, this._dx);
  29443. }
  29444. };
  29445. /**
  29446. * @author Richard Davey <rich@photonstorm.com>
  29447. * @copyright 2013 Photon Storm Ltd.
  29448. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  29449. */
  29450. /**
  29451. * The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than
  29452. * the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body.
  29453. *
  29454. * @class Phaser.Physics.Arcade.Body
  29455. * @classdesc Arcade Physics Body Constructor
  29456. * @constructor
  29457. * @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to.
  29458. */
  29459. Phaser.Physics.Arcade.Body = function (sprite) {
  29460. /**
  29461. * @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
  29462. */
  29463. this.sprite = sprite;
  29464. /**
  29465. * @property {Phaser.Game} game - Local reference to game.
  29466. */
  29467. this.game = sprite.game;
  29468. /**
  29469. * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
  29470. */
  29471. this.offset = new Phaser.Point();
  29472. /**
  29473. * @property {number} x - The x position of the physics body.
  29474. * @readonly
  29475. */
  29476. this.x = sprite.x;
  29477. /**
  29478. * @property {number} y - The y position of the physics body.
  29479. * @readonly
  29480. */
  29481. this.y = sprite.y;
  29482. /**
  29483. * @property {number} preX - The previous x position of the physics body.
  29484. * @readonly
  29485. */
  29486. this.preX = sprite.x;
  29487. /**
  29488. * @property {number} preY - The previous y position of the physics body.
  29489. * @readonly
  29490. */
  29491. this.preY = sprite.y;
  29492. /**
  29493. * @property {number} preRotation - The previous rotation of the physics body.
  29494. * @readonly
  29495. */
  29496. this.preRotation = sprite.angle;
  29497. /**
  29498. * @property {number} screenX - The x position of the physics body translated to screen space.
  29499. * @readonly
  29500. */
  29501. this.screenX = sprite.x;
  29502. /**
  29503. * @property {number} screenY - The y position of the physics body translated to screen space.
  29504. * @readonly
  29505. */
  29506. this.screenY = sprite.y;
  29507. /**
  29508. * @property {number} sourceWidth - The un-scaled original size.
  29509. * @readonly
  29510. */
  29511. this.sourceWidth = sprite.currentFrame.sourceSizeW;
  29512. /**
  29513. * @property {number} sourceHeight - The un-scaled original size.
  29514. * @readonly
  29515. */
  29516. this.sourceHeight = sprite.currentFrame.sourceSizeH;
  29517. /**
  29518. * @property {number} width - The calculated width of the physics body.
  29519. */
  29520. this.width = sprite.currentFrame.sourceSizeW;
  29521. /**
  29522. * @property .numInternal ID cache
  29523. */
  29524. this.height = sprite.currentFrame.sourceSizeH;
  29525. /**
  29526. * @property {number} halfWidth - The calculated width / 2 of the physics body.
  29527. */
  29528. this.halfWidth = Math.floor(sprite.currentFrame.sourceSizeW / 2);
  29529. /**
  29530. * @property {number} halfHeight - The calculated height / 2 of the physics body.
  29531. */
  29532. this.halfHeight = Math.floor(sprite.currentFrame.sourceSizeH / 2);
  29533. /**
  29534. * @property {Phaser.Point} center - The center coordinate of the Physics Body.
  29535. */
  29536. this.center = new Phaser.Point(this.x + this.halfWidth, this.y + this.halfHeight);
  29537. /**
  29538. * @property {number} _sx - Internal cache var.
  29539. * @private
  29540. */
  29541. this._sx = sprite.scale.x;
  29542. /**
  29543. * @property {number} _sy - Internal cache var.
  29544. * @private
  29545. */
  29546. this._sy = sprite.scale.y;
  29547. /**
  29548. * @property {Phaser.Point} velocity - The velocity in pixels per second sq. of the Body.
  29549. */
  29550. this.velocity = new Phaser.Point();
  29551. /**
  29552. * @property {Phaser.Point} acceleration - The velocity in pixels per second sq. of the Body.
  29553. */
  29554. this.acceleration = new Phaser.Point();
  29555. /**
  29556. * @property {Phaser.Point} drag - The drag applied to the motion of the Body.
  29557. */
  29558. this.drag = new Phaser.Point();
  29559. /**
  29560. * @property {Phaser.Point} gravity - A private Gravity setting for the Body.
  29561. */
  29562. this.gravity = new Phaser.Point();
  29563. /**
  29564. * @property {Phaser.Point} bounce - The elasticitiy of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity.
  29565. */
  29566. this.bounce = new Phaser.Point();
  29567. /**
  29568. * @property {Phaser.Point} maxVelocity - The maximum velocity in pixels per second sq. that the Body can reach.
  29569. * @default
  29570. */
  29571. this.maxVelocity = new Phaser.Point(10000, 10000);
  29572. /**
  29573. * @property {number} angularVelocity - The angular velocity in pixels per second sq. of the Body.
  29574. * @default
  29575. */
  29576. this.angularVelocity = 0;
  29577. /**
  29578. * @property {number} angularAcceleration - The angular acceleration in pixels per second sq. of the Body.
  29579. * @default
  29580. */
  29581. this.angularAcceleration = 0;
  29582. /**
  29583. * @property {number} angularDrag - The angular drag applied to the rotation of the Body.
  29584. * @default
  29585. */
  29586. this.angularDrag = 0;
  29587. /**
  29588. * @property {number} maxAngular - The maximum angular velocity in pixels per second sq. that the Body can reach.
  29589. * @default
  29590. */
  29591. this.maxAngular = 1000;
  29592. /**
  29593. * @property {number} mass - The mass of the Body.
  29594. * @default
  29595. */
  29596. this.mass = 1;
  29597. /**
  29598. * @property {boolean} skipQuadTree - If the Body is an irregular shape you can set this to true to avoid it being added to the World quad tree.
  29599. * @default
  29600. */
  29601. this.skipQuadTree = false;
  29602. /**
  29603. * @property {Array} quadTreeIDs - Internal ID cache.
  29604. * @protected
  29605. */
  29606. this.quadTreeIDs = [];
  29607. /**
  29608. * @property {number} quadTreeIndex - Internal ID cache.
  29609. * @protected
  29610. */
  29611. this.quadTreeIndex = -1;
  29612. // Allow collision
  29613. /**
  29614. * Set the allowCollision properties to control which directions collision is processed for this Body.
  29615. * For example allowCollision.up = false means it won't collide when the collision happened while moving up.
  29616. * @property {object} allowCollision - An object containing allowed collision.
  29617. */
  29618. this.allowCollision = { none: false, any: true, up: true, down: true, left: true, right: true };
  29619. /**
  29620. * This object is populated with boolean values when the Body collides with another.
  29621. * touching.up = true means the collision happened to the top of this Body for example.
  29622. * @property {object} touching - An object containing touching results.
  29623. */
  29624. this.touching = { none: true, up: false, down: false, left: false, right: false };
  29625. /**
  29626. * This object is populated with previous touching values from the bodies previous collision.
  29627. * @property {object} wasTouching - An object containing previous touching results.
  29628. */
  29629. this.wasTouching = { none: true, up: false, down: false, left: false, right: false };
  29630. /**
  29631. * @property {number} facing - A const reference to the direction the Body is traveling or facing.
  29632. * @default
  29633. */
  29634. this.facing = Phaser.NONE;
  29635. /**
  29636. * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies.
  29637. * @default
  29638. */
  29639. this.immovable = false;
  29640. /**
  29641. * @property {boolean} moves - Set to true to allow the Physics system to move this Body, other false to move it manually.
  29642. * @default
  29643. */
  29644. this.moves = true;
  29645. /**
  29646. * @property {number} rotation - The amount the Body is rotated.
  29647. * @default
  29648. */
  29649. this.rotation = 0;
  29650. /**
  29651. * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc)
  29652. * @default
  29653. */
  29654. this.allowRotation = true;
  29655. /**
  29656. * @property {boolean} allowGravity - Allow this Body to be influenced by the global Gravity?
  29657. * @default
  29658. */
  29659. this.allowGravity = true;
  29660. /**
  29661. * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate.
  29662. * Used in combination with your own collision processHandler you can create whatever type of collision response you need.
  29663. * @property {boolean} customSeparateX - Use a custom separation system or the built-in one?
  29664. * @default
  29665. */
  29666. this.customSeparateX = false;
  29667. /**
  29668. * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate.
  29669. * Used in combination with your own collision processHandler you can create whatever type of collision response you need.
  29670. * @property {boolean} customSeparateY - Use a custom separation system or the built-in one?
  29671. * @default
  29672. */
  29673. this.customSeparateY = false;
  29674. /**
  29675. * When this body collides with another, the amount of overlap is stored here.
  29676. * @property {number} overlapX - The amount of horizontal overlap during the collision.
  29677. */
  29678. this.overlapX = 0;
  29679. /**
  29680. * When this body collides with another, the amount of overlap is stored here.
  29681. * @property {number} overlapY - The amount of vertical overlap during the collision.
  29682. */
  29683. this.overlapY = 0;
  29684. /**
  29685. * @property {Phaser.Rectangle} hullX - The dynamically calculated hull used during collision.
  29686. */
  29687. this.hullX = new Phaser.Rectangle();
  29688. /**
  29689. * @property {Phaser.Rectangle} hullY - The dynamically calculated hull used during collision.
  29690. */
  29691. this.hullY = new Phaser.Rectangle();
  29692. /**
  29693. * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true.
  29694. * @property {boolean} embedded - Body embed value.
  29695. */
  29696. this.embedded = false;
  29697. /**
  29698. * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
  29699. * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
  29700. */
  29701. this.collideWorldBounds = false;
  29702. };
  29703. Phaser.Physics.Arcade.Body.prototype = {
  29704. /**
  29705. * Internal method.
  29706. *
  29707. * @method Phaser.Physics.Arcade#updateBounds
  29708. * @protected
  29709. */
  29710. updateBounds: function (centerX, centerY, scaleX, scaleY) {
  29711. if (scaleX != this._sx || scaleY != this._sy)
  29712. {
  29713. this.width = this.sourceWidth * scaleX;
  29714. this.height = this.sourceHeight * scaleY;
  29715. this.halfWidth = Math.floor(this.width / 2);
  29716. this.halfHeight = Math.floor(this.height / 2);
  29717. this._sx = scaleX;
  29718. this._sy = scaleY;
  29719. this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight);
  29720. }
  29721. },
  29722. /**
  29723. * Internal method.
  29724. *
  29725. * @method Phaser.Physics.Arcade#preUpdate
  29726. * @protected
  29727. */
  29728. preUpdate: function () {
  29729. // Store and reset collision flags
  29730. this.wasTouching.none = this.touching.none;
  29731. this.wasTouching.up = this.touching.up;
  29732. this.wasTouching.down = this.touching.down;
  29733. this.wasTouching.left = this.touching.left;
  29734. this.wasTouching.right = this.touching.right;
  29735. this.touching.none = true;
  29736. this.touching.up = false;
  29737. this.touching.down = false;
  29738. this.touching.left = false;
  29739. this.touching.right = false;
  29740. this.embedded = false;
  29741. this.screenX = (this.sprite.worldTransform[2] - (this.sprite.anchor.x * this.width)) + this.offset.x;
  29742. this.screenY = (this.sprite.worldTransform[5] - (this.sprite.anchor.y * this.height)) + this.offset.y;
  29743. this.preX = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x;
  29744. this.preY = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y;
  29745. this.preRotation = this.sprite.angle;
  29746. this.x = this.preX;
  29747. this.y = this.preY;
  29748. this.rotation = this.preRotation;
  29749. if (this.moves)
  29750. {
  29751. this.game.physics.updateMotion(this);
  29752. if (this.collideWorldBounds)
  29753. {
  29754. this.checkWorldBounds();
  29755. }
  29756. this.updateHulls();
  29757. }
  29758. if (this.skipQuadTree === false && this.allowCollision.none === false && this.sprite.visible && this.sprite.alive)
  29759. {
  29760. this.quadTreeIDs = [];
  29761. this.quadTreeIndex = -1;
  29762. this.game.physics.quadTree.insert(this);
  29763. }
  29764. },
  29765. /**
  29766. * Internal method.
  29767. *
  29768. * @method Phaser.Physics.Arcade#postUpdate
  29769. * @protected
  29770. */
  29771. postUpdate: function () {
  29772. if (this.deltaX() < 0)
  29773. {
  29774. this.facing = Phaser.LEFT;
  29775. }
  29776. else if (this.deltaX() > 0)
  29777. {
  29778. this.facing = Phaser.RIGHT;
  29779. }
  29780. if (this.deltaY() < 0)
  29781. {
  29782. this.facing = Phaser.UP;
  29783. }
  29784. else if (this.deltaY() > 0)
  29785. {
  29786. this.facing = Phaser.DOWN;
  29787. }
  29788. if (this.deltaX() !== 0 || this.deltaY() !== 0)
  29789. {
  29790. this.sprite.x += this.deltaX();
  29791. this.sprite.y += this.deltaY();
  29792. this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight);
  29793. }
  29794. if (this.allowRotation)
  29795. {
  29796. this.sprite.angle += this.deltaZ();
  29797. }
  29798. },
  29799. /**
  29800. * Internal method.
  29801. *
  29802. * @method Phaser.Physics.Arcade#updateHulls
  29803. * @protected
  29804. */
  29805. updateHulls: function () {
  29806. this.hullX.setTo(this.x, this.preY, this.width, this.height);
  29807. this.hullY.setTo(this.preX, this.y, this.width, this.height);
  29808. },
  29809. /**
  29810. * Internal method.
  29811. *
  29812. * @method Phaser.Physics.Arcade#checkWorldBounds
  29813. * @protected
  29814. */
  29815. checkWorldBounds: function () {
  29816. if (this.x < this.game.world.bounds.x)
  29817. {
  29818. this.x = this.game.world.bounds.x;
  29819. this.velocity.x *= -this.bounce.x;
  29820. }
  29821. else if (this.right > this.game.world.bounds.right)
  29822. {
  29823. this.x = this.game.world.bounds.right - this.width;
  29824. this.velocity.x *= -this.bounce.x;
  29825. }
  29826. if (this.y < this.game.world.bounds.y)
  29827. {
  29828. this.y = this.game.world.bounds.y;
  29829. this.velocity.y *= -this.bounce.y;
  29830. }
  29831. else if (this.bottom > this.game.world.bounds.bottom)
  29832. {
  29833. this.y = this.game.world.bounds.bottom - this.height;
  29834. this.velocity.y *= -this.bounce.y;
  29835. }
  29836. },
  29837. /**
  29838. * You can modify the size of the physics Body to be any dimension you need.
  29839. * So it could be smaller or larger than the parent Sprite. You can also control the x and y offset, which
  29840. * is the position of the Body relative to the top-left of the Sprite.
  29841. *
  29842. * @method Phaser.Physics.Arcade#setSize
  29843. * @param {number} width - The width of the Body.
  29844. * @param {number} height - The height of the Body.
  29845. * @param {number} offsetX - The X offset of the Body from the Sprite position.
  29846. * @param {number} offsetY - The Y offset of the Body from the Sprite position.
  29847. */
  29848. setSize: function (width, height, offsetX, offsetY) {
  29849. offsetX = offsetX || this.offset.x;
  29850. offsetY = offsetY || this.offset.y;
  29851. this.sourceWidth = width;
  29852. this.sourceHeight = height;
  29853. this.width = this.sourceWidth * this._sx;
  29854. this.height = this.sourceHeight * this._sy;
  29855. this.halfWidth = Math.floor(this.width / 2);
  29856. this.halfHeight = Math.floor(this.height / 2);
  29857. this.offset.setTo(offsetX, offsetY);
  29858. this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight);
  29859. },
  29860. /**
  29861. * Resets all Body values (velocity, acceleration, rotation, etc)
  29862. *
  29863. * @method Phaser.Physics.Arcade#reset
  29864. */
  29865. reset: function () {
  29866. this.velocity.setTo(0, 0);
  29867. this.acceleration.setTo(0, 0);
  29868. this.angularVelocity = 0;
  29869. this.angularAcceleration = 0;
  29870. this.preX = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x;
  29871. this.preY = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y;
  29872. this.preRotation = this.sprite.angle;
  29873. this.x = this.preX;
  29874. this.y = this.preY;
  29875. this.rotation = this.preRotation;
  29876. this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight);
  29877. },
  29878. /**
  29879. * Returns the absolute delta x value.
  29880. *
  29881. * @method Phaser.Physics.Arcade.Body#deltaAbsX
  29882. * @return {number} The absolute delta value.
  29883. */
  29884. deltaAbsX: function () {
  29885. return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX());
  29886. },
  29887. /**
  29888. * Returns the absolute delta y value.
  29889. *
  29890. * @method Phaser.Physics.Arcade.Body#deltaAbsY
  29891. * @return {number} The absolute delta value.
  29892. */
  29893. deltaAbsY: function () {
  29894. return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY());
  29895. },
  29896. /**
  29897. * Returns the delta x value. The difference between Body.x now and in the previous step.
  29898. *
  29899. * @method Phaser.Physics.Arcade.Body#deltaX
  29900. * @return {number} The delta value.
  29901. */
  29902. deltaX: function () {
  29903. return this.x - this.preX;
  29904. },
  29905. /**
  29906. * Returns the delta y value. The difference between Body.y now and in the previous step.
  29907. *
  29908. * @method Phaser.Physics.Arcade.Body#deltaY
  29909. * @return {number} The delta value.
  29910. */
  29911. deltaY: function () {
  29912. return this.y - this.preY;
  29913. },
  29914. deltaZ: function () {
  29915. return this.rotation - this.preRotation;
  29916. }
  29917. };
  29918. /**
  29919. * @name Phaser.Physics.Arcade.Body#bottom
  29920. * @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
  29921. */
  29922. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", {
  29923. /**
  29924. * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property.
  29925. * @method bottom
  29926. * @return {number}
  29927. */
  29928. get: function () {
  29929. return this.y + this.height;
  29930. },
  29931. /**
  29932. * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property.
  29933. * @method bottom
  29934. * @param {number} value
  29935. */
  29936. set: function (value) {
  29937. if (value <= this.y)
  29938. {
  29939. this.height = 0;
  29940. }
  29941. else
  29942. {
  29943. this.height = (this.y - value);
  29944. }
  29945. }
  29946. });
  29947. /**
  29948. * @name Phaser.Physics.Arcade.Body#right
  29949. * @property {number} right - The right value of this Body (same as Body.x + Body.width)
  29950. */
  29951. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", {
  29952. /**
  29953. * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties.
  29954. * However it does affect the width property.
  29955. * @method right
  29956. * @return {number}
  29957. */
  29958. get: function () {
  29959. return this.x + this.width;
  29960. },
  29961. /**
  29962. * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties.
  29963. * However it does affect the width property.
  29964. * @method right
  29965. * @param {number} value
  29966. */
  29967. set: function (value) {
  29968. if (value <= this.x)
  29969. {
  29970. this.width = 0;
  29971. }
  29972. else
  29973. {
  29974. this.width = this.x + value;
  29975. }
  29976. }
  29977. });
  29978. /**
  29979. * @author Richard Davey <rich@photonstorm.com>
  29980. * @copyright 2013 Photon Storm Ltd.
  29981. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  29982. */
  29983. /**
  29984. * Phaser.Particles is the Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it.
  29985. *
  29986. * @class Phaser.Particles
  29987. * @classdesc Phaser Particles
  29988. * @constructor
  29989. * @param {Phaser.Game} game - A reference to the currently running game.
  29990. */
  29991. Phaser.Particles = function (game) {
  29992. /**
  29993. * @property {Phaser.Game} game - A reference to the currently running Game.
  29994. */
  29995. this.game = game;
  29996. /**
  29997. * @property {object} emitters - Internal emitters store.
  29998. */
  29999. this.emitters = {};
  30000. /**
  30001. * @property {number} ID -
  30002. * @default
  30003. */
  30004. this.ID = 0;
  30005. };
  30006. Phaser.Particles.prototype = {
  30007. /**
  30008. * Adds a new Particle Emitter to the Particle Manager.
  30009. * @method Phaser.Particles#add
  30010. * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager.
  30011. * @return {Phaser.Emitter} The emitter that was added.
  30012. */
  30013. add: function (emitter) {
  30014. this.emitters[emitter.name] = emitter;
  30015. return emitter;
  30016. },
  30017. /**
  30018. * Removes an existing Particle Emitter from the Particle Manager.
  30019. * @method Phaser.Particles#remove
  30020. * @param {Phaser.Emitter} emitter - The emitter to remove.
  30021. */
  30022. remove: function (emitter) {
  30023. delete this.emitters[emitter.name];
  30024. },
  30025. /**
  30026. * Called by the core game loop. Updates all Emitters who have their exists value set to true.
  30027. * @method Phaser.Particles#update
  30028. * @protected
  30029. */
  30030. update: function () {
  30031. for (var key in this.emitters)
  30032. {
  30033. if (this.emitters[key].exists)
  30034. {
  30035. this.emitters[key].update();
  30036. }
  30037. }
  30038. }
  30039. };
  30040. Phaser.Particles.Arcade = {}
  30041. /**
  30042. * @author Richard Davey <rich@photonstorm.com>
  30043. * @copyright 2013 Photon Storm Ltd.
  30044. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  30045. */
  30046. /**
  30047. * Phaser - ArcadeEmitter
  30048. *
  30049. * @class Phaser.Particles.Arcade.Emitter
  30050. * @classdesc Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
  30051. * continuous effects like rain and fire. All it really does is launch Particle objects out
  30052. * at set intervals, and fixes their positions and velocities accorindgly.
  30053. * @constructor
  30054. * @extends Phaser.Group
  30055. * @param {Phaser.Game} game - Current game instance.
  30056. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  30057. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  30058. * @param {number} [maxParticles=50] - The total number of particles in this emitter..
  30059. */
  30060. Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) {
  30061. /**
  30062. * The total number of particles in this emitter.
  30063. * @property {number} maxParticles - The total number of particles in this emitter..
  30064. * @default
  30065. */
  30066. this.maxParticles = maxParticles || 50;
  30067. Phaser.Group.call(this, game);
  30068. /**
  30069. * @property {string} name - Description.
  30070. */
  30071. this.name = 'emitter' + this.game.particles.ID++;
  30072. /**
  30073. * @property {Description} type - Description.
  30074. */
  30075. this.type = Phaser.EMITTER;
  30076. /**
  30077. * @property {number} x - The X position of the top left corner of the emitter in world space.
  30078. * @default
  30079. */
  30080. this.x = 0;
  30081. /**
  30082. * @property {number} y - The Y position of the top left corner of emitter in world space.
  30083. * @default
  30084. */
  30085. this.y = 0;
  30086. /**
  30087. * @property {number} width - The width of the emitter. Particles can be randomly generated from anywhere within this box.
  30088. * @default
  30089. */
  30090. this.width = 1;
  30091. /**
  30092. * @property {number} height - The height of the emitter. Particles can be randomly generated from anywhere within this box.
  30093. * @default
  30094. */
  30095. this.height = 1;
  30096. /**
  30097. * The minimum possible velocity of a particle.
  30098. * The default value is (-100,-100).
  30099. * @property {Phaser.Point} minParticleSpeed
  30100. */
  30101. this.minParticleSpeed = new Phaser.Point(-100, -100);
  30102. /**
  30103. * The maximum possible velocity of a particle.
  30104. * The default value is (100,100).
  30105. * @property {Phaser.Point} maxParticleSpeed
  30106. */
  30107. this.maxParticleSpeed = new Phaser.Point(100, 100);
  30108. /**
  30109. * The minimum possible scale of a particle.
  30110. * The default value is 1.
  30111. * @property {number} minParticleScale
  30112. * @default
  30113. */
  30114. this.minParticleScale = 1;
  30115. /**
  30116. * The maximum possible scale of a particle.
  30117. * The default value is 1.
  30118. * @property {number} maxParticleScale
  30119. * @default
  30120. */
  30121. this.maxParticleScale = 1;
  30122. /**
  30123. * The minimum possible angular velocity of a particle. The default value is -360.
  30124. * @property {number} minRotation
  30125. * @default
  30126. */
  30127. this.minRotation = -360;
  30128. /**
  30129. * The maximum possible angular velocity of a particle. The default value is 360.
  30130. * @property {number} maxRotation
  30131. * @default
  30132. */
  30133. this.maxRotation = 360;
  30134. /**
  30135. * Sets the <code>gravity.y</code> of each particle to this value on launch.
  30136. * @property {number} gravity
  30137. * @default
  30138. */
  30139. this.gravity = 2;
  30140. /**
  30141. * Set your own particle class type here.
  30142. * @property {Description} particleClass
  30143. * @default
  30144. */
  30145. this.particleClass = null;
  30146. /**
  30147. * The X and Y drag component of particles launched from the emitter.
  30148. * @property {Phaser.Point} particleDrag
  30149. */
  30150. this.particleDrag = new Phaser.Point();
  30151. /**
  30152. * The angular drag component of particles launched from the emitter if they are rotating.
  30153. * @property {number} angularDrag
  30154. * @default
  30155. */
  30156. this.angularDrag = 0;
  30157. /**
  30158. * How often a particle is emitted in ms (if emitter is started with Explode === false).
  30159. * @property {boolean} frequency
  30160. * @default
  30161. */
  30162. this.frequency = 100;
  30163. /**
  30164. * How long each particle lives once it is emitted in ms. Default is 2 seconds.
  30165. * Set lifespan to 'zero' for particles to live forever.
  30166. * @property {number} lifespan
  30167. * @default
  30168. */
  30169. this.lifespan = 2000;
  30170. /**
  30171. * How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce.
  30172. * @property {Phaser.Point} bounce
  30173. */
  30174. this.bounce = new Phaser.Point();
  30175. /**
  30176. * Internal helper for deciding how many particles to launch.
  30177. * @property {number} _quantity
  30178. * @private
  30179. * @default
  30180. */
  30181. this._quantity = 0;
  30182. /**
  30183. * Internal helper for deciding when to launch particles or kill them.
  30184. * @property {number} _timer
  30185. * @private
  30186. * @default
  30187. */
  30188. this._timer = 0;
  30189. /**
  30190. * Internal counter for figuring out how many particles to launch.
  30191. * @property {number} _counter
  30192. * @private
  30193. * @default
  30194. */
  30195. this._counter = 0;
  30196. /**
  30197. * Internal helper for the style of particle emission (all at once, or one at a time).
  30198. * @property {boolean} _explode
  30199. * @private
  30200. * @default
  30201. */
  30202. this._explode = true;
  30203. /**
  30204. * Determines whether the emitter is currently emitting particles.
  30205. * It is totally safe to directly toggle this.
  30206. * @property {boolean} on
  30207. * @default
  30208. */
  30209. this.on = false;
  30210. /**
  30211. * Determines whether the emitter is being updated by the core game loop.
  30212. * @property {boolean} exists
  30213. * @default
  30214. */
  30215. this.exists = true;
  30216. /**
  30217. * The point the particles are emitted from.
  30218. * Emitter.x and Emitter.y control the containers location, which updates all current particles
  30219. * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
  30220. * @property {boolean} emitX
  30221. */
  30222. this.emitX = x;
  30223. /**
  30224. * The point the particles are emitted from.
  30225. * Emitter.x and Emitter.y control the containers location, which updates all current particles
  30226. * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
  30227. * @property {boolean} emitY
  30228. */
  30229. this.emitY = y;
  30230. };
  30231. Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype);
  30232. Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter;
  30233. /**
  30234. * Called automatically by the game loop, decides when to launch particles and when to "die".
  30235. * @method Phaser.Particles.Arcade.Emitter#update
  30236. */
  30237. Phaser.Particles.Arcade.Emitter.prototype.update = function () {
  30238. if (this.on)
  30239. {
  30240. if (this._explode)
  30241. {
  30242. this._counter = 0;
  30243. do
  30244. {
  30245. this.emitParticle();
  30246. this._counter++;
  30247. }
  30248. while (this._counter < this._quantity);
  30249. this.on = false;
  30250. }
  30251. else
  30252. {
  30253. if (this.game.time.now >= this._timer)
  30254. {
  30255. this.emitParticle();
  30256. this._counter++;
  30257. if (this._quantity > 0)
  30258. {
  30259. if (this._counter >= this._quantity)
  30260. {
  30261. this.on = false;
  30262. }
  30263. }
  30264. this._timer = this.game.time.now + this.frequency;
  30265. }
  30266. }
  30267. }
  30268. }
  30269. /**
  30270. * This function generates a new array of particle sprites to attach to the emitter.
  30271. *
  30272. * @method Phaser.Particles.Arcade.Emitter#makeParticles
  30273. * @param {Description} keys - Description.
  30274. * @param {number} frames - Description.
  30275. * @param {number} quantity - The number of particles to generate when using the "create from image" option.
  30276. * @param {number} collide - Description.
  30277. * @param {boolean} collideWorldBounds - Description.
  30278. * @return This Emitter instance (nice for chaining stuff together, if you're into that).
  30279. */
  30280. Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds) {
  30281. if (typeof frames == 'undefined')
  30282. {
  30283. frames = 0;
  30284. }
  30285. quantity = quantity || this.maxParticles;
  30286. collide = collide || 0;
  30287. if (typeof collideWorldBounds == 'undefined')
  30288. {
  30289. collideWorldBounds = false;
  30290. }
  30291. var particle;
  30292. var i = 0;
  30293. var rndKey = keys;
  30294. var rndFrame = 0;
  30295. while (i < quantity)
  30296. {
  30297. if (this.particleClass == null)
  30298. {
  30299. if (typeof keys == 'object')
  30300. {
  30301. rndKey = this.game.rnd.pick(keys);
  30302. }
  30303. if (typeof frames == 'object')
  30304. {
  30305. rndFrame = this.game.rnd.pick(frames);
  30306. }
  30307. particle = new Phaser.Sprite(this.game, 0, 0, rndKey, rndFrame);
  30308. }
  30309. // else
  30310. // {
  30311. // particle = new this.particleClass(this.game);
  30312. // }
  30313. if (collide > 0)
  30314. {
  30315. particle.body.allowCollision.any = true;
  30316. particle.body.allowCollision.none = false;
  30317. }
  30318. else
  30319. {
  30320. particle.body.allowCollision.none = true;
  30321. }
  30322. particle.body.collideWorldBounds = collideWorldBounds;
  30323. particle.exists = false;
  30324. particle.visible = false;
  30325. // Center the origin for rotation assistance
  30326. particle.anchor.setTo(0.5, 0.5);
  30327. this.add(particle);
  30328. i++;
  30329. }
  30330. return this;
  30331. }
  30332. /**
  30333. * Call this function to turn off all the particles and the emitter.
  30334. * @method Phaser.Particles.Arcade.Emitter#kill
  30335. */
  30336. Phaser.Particles.Arcade.Emitter.prototype.kill = function () {
  30337. this.on = false;
  30338. this.alive = false;
  30339. this.exists = false;
  30340. }
  30341. /**
  30342. * Handy for bringing game objects "back to life". Just sets alive and exists back to true.
  30343. * In practice, this is most often called by <code>Object.reset()</code>.
  30344. * @method Phaser.Particles.Arcade.Emitter#revive
  30345. */
  30346. Phaser.Particles.Arcade.Emitter.prototype.revive = function () {
  30347. this.alive = true;
  30348. this.exists = true;
  30349. }
  30350. /**
  30351. * Call this function to start emitting particles.
  30352. * @method Phaser.Particles.Arcade.Emitter#start
  30353. * @param {boolean} explode - Whether the particles should all burst out at once.
  30354. * @param {number} lifespan - How long each particle lives once emitted. 0 = forever.
  30355. * @param {number} frequency - Ignored if Explode is set to true. Frequency is how often to emit a particle in ms.
  30356. * @param {number} quantity - How many particles to launch. 0 = "all of the particles".
  30357. */
  30358. Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, quantity) {
  30359. if (typeof explode !== 'boolean')
  30360. {
  30361. explode = true;
  30362. }
  30363. lifespan = lifespan || 0;
  30364. // How many ms between emissions?
  30365. frequency = frequency || 250;
  30366. // Total number of particles to emit
  30367. quantity = quantity || 0;
  30368. this.revive();
  30369. this.visible = true;
  30370. this.on = true;
  30371. this._explode = explode;
  30372. this.lifespan = lifespan;
  30373. this.frequency = frequency;
  30374. if (explode)
  30375. {
  30376. this._quantity = quantity;
  30377. }
  30378. else
  30379. {
  30380. this._quantity += quantity;
  30381. }
  30382. this._counter = 0;
  30383. this._timer = this.game.time.now + frequency;
  30384. }
  30385. /**
  30386. * This function can be used both internally and externally to emit the next particle.
  30387. * @method Phaser.Particles.Arcade.Emitter#emitParticle
  30388. */
  30389. Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function () {
  30390. var particle = this.getFirstExists(false);
  30391. if (particle == null)
  30392. {
  30393. return;
  30394. }
  30395. if (this.width > 1 || this.height > 1)
  30396. {
  30397. particle.reset(this.game.rnd.integerInRange(this.left, this.right), this.game.rnd.integerInRange(this.top, this.bottom));
  30398. }
  30399. else
  30400. {
  30401. particle.reset(this.emitX, this.emitY);
  30402. }
  30403. particle.lifespan = this.lifespan;
  30404. particle.body.bounce.setTo(this.bounce.x, this.bounce.y);
  30405. if (this.minParticleSpeed.x != this.maxParticleSpeed.x)
  30406. {
  30407. particle.body.velocity.x = this.game.rnd.integerInRange(this.minParticleSpeed.x, this.maxParticleSpeed.x);
  30408. }
  30409. else
  30410. {
  30411. particle.body.velocity.x = this.minParticleSpeed.x;
  30412. }
  30413. if (this.minParticleSpeed.y != this.maxParticleSpeed.y)
  30414. {
  30415. particle.body.velocity.y = this.game.rnd.integerInRange(this.minParticleSpeed.y, this.maxParticleSpeed.y);
  30416. }
  30417. else
  30418. {
  30419. particle.body.velocity.y = this.minParticleSpeed.y;
  30420. }
  30421. particle.body.gravity.y = this.gravity;
  30422. if (this.minRotation != this.maxRotation)
  30423. {
  30424. particle.body.angularVelocity = this.game.rnd.integerInRange(this.minRotation, this.maxRotation);
  30425. }
  30426. else
  30427. {
  30428. particle.body.angularVelocity = this.minRotation;
  30429. }
  30430. if (this.minParticleScale !== 1 || this.maxParticleScale !== 1)
  30431. {
  30432. var scale = this.game.rnd.realInRange(this.minParticleScale, this.maxParticleScale);
  30433. particle.scale.setTo(scale, scale);
  30434. }
  30435. particle.body.drag.x = this.particleDrag.x;
  30436. particle.body.drag.y = this.particleDrag.y;
  30437. particle.body.angularDrag = this.angularDrag;
  30438. }
  30439. /**
  30440. * A more compact way of setting the width and height of the emitter.
  30441. * @method Phaser.Particles.Arcade.Emitter#setSize
  30442. * @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions).
  30443. * @param {number} height - The desired height of the emitter.
  30444. */
  30445. Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) {
  30446. this.width = width;
  30447. this.height = height;
  30448. }
  30449. /**
  30450. * A more compact way of setting the X velocity range of the emitter.
  30451. * @method Phaser.Particles.Arcade.Emitter#setXSpeed
  30452. * @param {number} min - The minimum value for this range.
  30453. * @param {number} max - The maximum value for this range.
  30454. */
  30455. Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) {
  30456. min = min || 0;
  30457. max = max || 0;
  30458. this.minParticleSpeed.x = min;
  30459. this.maxParticleSpeed.x = max;
  30460. }
  30461. /**
  30462. * A more compact way of setting the Y velocity range of the emitter.
  30463. * @method Phaser.Particles.Arcade.Emitter#setYSpeed
  30464. * @param {number} min - The minimum value for this range.
  30465. * @param {number} max - The maximum value for this range.
  30466. */
  30467. Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) {
  30468. min = min || 0;
  30469. max = max || 0;
  30470. this.minParticleSpeed.y = min;
  30471. this.maxParticleSpeed.y = max;
  30472. }
  30473. /**
  30474. * A more compact way of setting the angular velocity constraints of the emitter.
  30475. * @method Phaser.Particles.Arcade.Emitter#setRotation
  30476. * @param {number} min - The minimum value for this range.
  30477. * @param {number} max - The maximum value for this range.
  30478. */
  30479. Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) {
  30480. min = min || 0;
  30481. max = max || 0;
  30482. this.minRotation = min;
  30483. this.maxRotation = max;
  30484. }
  30485. /**
  30486. * Change the emitter's midpoint to match the midpoint of a <code>Object</code>.
  30487. * @method Phaser.Particles.Arcade.Emitter#at
  30488. * @param {object} object - The <code>Object</code> that you want to sync up with.
  30489. */
  30490. Phaser.Particles.Arcade.Emitter.prototype.at = function (object) {
  30491. this.emitX = object.center.x;
  30492. this.emitY = object.center.y;
  30493. }
  30494. /**
  30495. * The emitters alpha value.
  30496. * @name Phaser.Particles.Arcade.Emitter#alpha
  30497. * @property {number} alpha - Gets or sets the alpha value of the Emitter.
  30498. */
  30499. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "alpha", {
  30500. get: function () {
  30501. return this._container.alpha;
  30502. },
  30503. set: function (value) {
  30504. this._container.alpha = value;
  30505. }
  30506. });
  30507. /**
  30508. * The emitter visible state.
  30509. * @name Phaser.Particles.Arcade.Emitter#visible
  30510. * @property {boolean} visible - Gets or sets the Emitter visible state.
  30511. */
  30512. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "visible", {
  30513. get: function () {
  30514. return this._container.visible;
  30515. },
  30516. set: function (value) {
  30517. this._container.visible = value;
  30518. }
  30519. });
  30520. /**
  30521. * @name Phaser.Particles.Arcade.Emitter#x
  30522. * @property {number} x - Gets or sets the x position of the Emitter.
  30523. */
  30524. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", {
  30525. get: function () {
  30526. return this.emitX;
  30527. },
  30528. set: function (value) {
  30529. this.emitX = value;
  30530. }
  30531. });
  30532. /**
  30533. * @name Phaser.Particles.Arcade.Emitter#y
  30534. * @property {number} y - Gets or sets the y position of the Emitter.
  30535. */
  30536. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", {
  30537. get: function () {
  30538. return this.emitY;
  30539. },
  30540. set: function (value) {
  30541. this.emitY = value;
  30542. }
  30543. });
  30544. /**
  30545. * @name Phaser.Particles.Arcade.Emitter#left
  30546. * @property {number} left - Gets the left position of the Emitter.
  30547. * @readonly
  30548. */
  30549. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", {
  30550. get: function () {
  30551. return Math.floor(this.x - (this.width / 2));
  30552. }
  30553. });
  30554. /**
  30555. * @name Phaser.Particles.Arcade.Emitter#right
  30556. * @property {number} right - Gets the right position of the Emitter.
  30557. * @readonly
  30558. */
  30559. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", {
  30560. get: function () {
  30561. return Math.floor(this.x + (this.width / 2));
  30562. }
  30563. });
  30564. /**
  30565. * @name Phaser.Particles.Arcade.Emitter#top
  30566. * @property {number} top - Gets the top position of the Emitter.
  30567. * @readonly
  30568. */
  30569. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", {
  30570. get: function () {
  30571. return Math.floor(this.y - (this.height / 2));
  30572. }
  30573. });
  30574. /**
  30575. * @name Phaser.Particles.Arcade.Emitter#bottom
  30576. * @property {number} bottom - Gets the bottom position of the Emitter.
  30577. * @readonly
  30578. */
  30579. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", {
  30580. get: function () {
  30581. return Math.floor(this.y + (this.height / 2));
  30582. }
  30583. });
  30584. /**
  30585. * @author Richard Davey <rich@photonstorm.com>
  30586. * @copyright 2013 Photon Storm Ltd.
  30587. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  30588. */
  30589. /**
  30590. * Create a new `Tile` object. Tiles live inside of Tilesets and are rendered via TilemapLayers.
  30591. *
  30592. * @class Phaser.Tile
  30593. * @classdesc A Tile is a single representation of a tile within a Tilemap.
  30594. * @constructor
  30595. * @param {Phaser.Tileset} tileset - The tileset this tile belongs to.
  30596. * @param {number} index - The index of this tile type in the core map data.
  30597. * @param {number} x - The x coordinate of this tile.
  30598. * @param {number} y - The y coordinate of this tile.
  30599. * @param {number} width - Width of the tile.
  30600. * @param {number} height - Height of the tile.
  30601. */
  30602. Phaser.Tile = function (tileset, index, x, y, width, height) {
  30603. /**
  30604. * @property {Phaser.Tileset} tileset - The tileset this tile belongs to.
  30605. */
  30606. this.tileset = tileset;
  30607. /**
  30608. * @property {number} index - The index of this tile within the tileset.
  30609. */
  30610. this.index = index;
  30611. /**
  30612. * @property {number} width - The width of the tile in pixels.
  30613. */
  30614. this.width = width;
  30615. /**
  30616. * @property {number} height - The height of the tile in pixels.
  30617. */
  30618. this.height = height;
  30619. /**
  30620. * @property {number} x - The top-left corner of the tile within the tileset.
  30621. */
  30622. this.x = x;
  30623. /**
  30624. * @property {number} y - The top-left corner of the tile within the tileset.
  30625. */
  30626. this.y = y;
  30627. // Any extra meta data info we need here
  30628. /**
  30629. * @property {number} mass - The virtual mass of the tile.
  30630. * @default
  30631. */
  30632. this.mass = 1.0;
  30633. /**
  30634. * @property {boolean} collideNone - Indicating this Tile doesn't collide at all.
  30635. * @default
  30636. */
  30637. this.collideNone = true;
  30638. /**
  30639. * @property {boolean} collideLeft - Indicating collide with any object on the left.
  30640. * @default
  30641. */
  30642. this.collideLeft = false;
  30643. /**
  30644. * @property {boolean} collideRight - Indicating collide with any object on the right.
  30645. * @default
  30646. */
  30647. this.collideRight = false;
  30648. /**
  30649. * @property {boolean} collideUp - Indicating collide with any object on the top.
  30650. * @default
  30651. */
  30652. this.collideUp = false;
  30653. /**
  30654. * @property {boolean} collideDown - Indicating collide with any object on the bottom.
  30655. * @default
  30656. */
  30657. this.collideDown = false;
  30658. /**
  30659. * @property {boolean} separateX - Enable separation at x-axis.
  30660. * @default
  30661. */
  30662. this.separateX = true;
  30663. /**
  30664. * @property {boolean} separateY - Enable separation at y-axis.
  30665. * @default
  30666. */
  30667. this.separateY = true;
  30668. /**
  30669. * @property {boolean} collisionCallback - Tilemap collision callback.
  30670. * @default
  30671. */
  30672. this.collisionCallback = null;
  30673. /**
  30674. * @property {boolean} collisionCallback - Tilemap collision callback.
  30675. * @default
  30676. */
  30677. this.collisionCallbackContext = this;
  30678. };
  30679. Phaser.Tile.prototype = {
  30680. /**
  30681. * Set callback to be called when this tilemap collides.
  30682. *
  30683. * @method Phaser.Tile#setCollisionCallback
  30684. * @param {Function} callback - Callback function.
  30685. * @param {object} context - Callback will be called with this context.
  30686. */
  30687. setCollisionCallback: function (callback, context) {
  30688. this.collisionCallbackContext = context;
  30689. this.collisionCallback = callback;
  30690. },
  30691. /**
  30692. * Clean up memory.
  30693. * @method Phaser.Tile#destroy
  30694. */
  30695. destroy: function () {
  30696. this.tileset = null;
  30697. },
  30698. /**
  30699. * Set collision settings on this tile.
  30700. * @method Phaser.Tile#setCollision
  30701. * @param {boolean} left - Indicating collide with any object on the left.
  30702. * @param {boolean} right - Indicating collide with any object on the right.
  30703. * @param {boolean} up - Indicating collide with any object on the top.
  30704. * @param {boolean} down - Indicating collide with any object on the bottom.
  30705. */
  30706. setCollision: function (left, right, up, down) {
  30707. this.collideLeft = left;
  30708. this.collideRight = right;
  30709. this.collideUp = up;
  30710. this.collideDown = down;
  30711. if (left || right || up || down)
  30712. {
  30713. this.collideNone = false;
  30714. }
  30715. else
  30716. {
  30717. this.collideNone = true;
  30718. }
  30719. },
  30720. /**
  30721. * Reset collision status flags.
  30722. * @method Phaser.Tile#resetCollision
  30723. */
  30724. resetCollision: function () {
  30725. this.collideNone = true;
  30726. this.collideLeft = false;
  30727. this.collideRight = false;
  30728. this.collideUp = false;
  30729. this.collideDown = false;
  30730. }
  30731. };
  30732. /**
  30733. * @name Phaser.Tile#bottom
  30734. * @property {number} bottom - The sum of the y and height properties.
  30735. * @readonly
  30736. */
  30737. Object.defineProperty(Phaser.Tile.prototype, "bottom", {
  30738. get: function () {
  30739. return this.y + this.height;
  30740. }
  30741. });
  30742. /**
  30743. * @name Phaser.Tile#right
  30744. * @property {number} right - The sum of the x and width properties.
  30745. * @readonly
  30746. */
  30747. Object.defineProperty(Phaser.Tile.prototype, "right", {
  30748. get: function () {
  30749. return this.x + this.width;
  30750. }
  30751. });
  30752. /**
  30753. * @author Richard Davey <rich@photonstorm.com>
  30754. * @copyright 2013 Photon Storm Ltd.
  30755. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  30756. */
  30757. /**
  30758. * A Tile Map object. A Tile map consists of a set of tile data and tile sets. It is rendered to the display using a TilemapLayer.
  30759. * A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around.
  30760. *
  30761. * @class Phaser.Tilemap
  30762. * @constructor
  30763. * @param {Phaser.Game} game - Game reference to the currently running game.
  30764. * @param {string} [key] - The key of the tilemap data as stored in the Cache.
  30765. */
  30766. Phaser.Tilemap = function (game, key) {
  30767. /**
  30768. * @property {Phaser.Game} game - A reference to the currently running Game.
  30769. */
  30770. this.game = game;
  30771. /**
  30772. * @property {array} layers - An array of Tilemap layers.
  30773. */
  30774. this.layers = null;
  30775. if (typeof key === 'string')
  30776. {
  30777. this.key = key;
  30778. this.layers = game.cache.getTilemapData(key).layers;
  30779. this.calculateIndexes();
  30780. }
  30781. else
  30782. {
  30783. this.layers = [];
  30784. }
  30785. /**
  30786. * @property {number} currentLayer - The current layer.
  30787. */
  30788. this.currentLayer = 0;
  30789. /**
  30790. * @property {array} debugMap - Map data used for debug values only.
  30791. */
  30792. this.debugMap = [];
  30793. /**
  30794. * @property {boolean} dirty - Internal rendering related flag.
  30795. */
  30796. this.dirty = false;
  30797. /**
  30798. * @property {array} _results - Internal var.
  30799. * @private
  30800. */
  30801. this._results = [];
  30802. /**
  30803. * @property {number} _tempA - Internal var.
  30804. * @private
  30805. */
  30806. this._tempA = 0;
  30807. /**
  30808. * @property {number} _tempB - Internal var.
  30809. * @private
  30810. */
  30811. this._tempB = 0;
  30812. };
  30813. /**
  30814. * @constant
  30815. * @type {number}
  30816. */
  30817. Phaser.Tilemap.CSV = 0;
  30818. /**
  30819. * @constant
  30820. * @type {number}
  30821. */
  30822. Phaser.Tilemap.TILED_JSON = 1;
  30823. Phaser.Tilemap.prototype = {
  30824. /**
  30825. * Creates an empty map of the given dimensions.
  30826. *
  30827. * @method Phaser.Tilemap#create
  30828. * @param {string} name - The name of the map (mostly used for debugging)
  30829. * @param {number} width - The width of the map in tiles.
  30830. * @param {number} height - The height of the map in tiles.
  30831. */
  30832. create: function (name, width, height) {
  30833. var data = [];
  30834. for (var y = 0; y < height; y++)
  30835. {
  30836. data[y] = [];
  30837. for (var x = 0; x < width; x++)
  30838. {
  30839. data[y][x] = 0;
  30840. }
  30841. }
  30842. this.layers.push({
  30843. name: name,
  30844. width: width,
  30845. height: height,
  30846. alpha: 1,
  30847. visible: true,
  30848. tileMargin: 0,
  30849. tileSpacing: 0,
  30850. format: Phaser.Tilemap.CSV,
  30851. data: data,
  30852. indexes: []
  30853. });
  30854. this.currentLayer = this.layers.length - 1;
  30855. this.dirty = true;
  30856. },
  30857. /**
  30858. * Internal function that calculates the tile indexes for the map data.
  30859. *
  30860. * @method Phaser.Tilemap#calculateIndexes
  30861. */
  30862. calculateIndexes: function () {
  30863. for (var layer = 0; layer < this.layers.length; layer++)
  30864. {
  30865. this.layers[layer].indexes = [];
  30866. for (var y = 0; y < this.layers[layer].height ; y++)
  30867. {
  30868. for (var x = 0; x < this.layers[layer].width; x++)
  30869. {
  30870. var idx = this.layers[layer].data[y][x];
  30871. if (this.layers[layer].indexes.indexOf(idx) === -1)
  30872. {
  30873. this.layers[layer].indexes.push(idx);
  30874. }
  30875. }
  30876. }
  30877. }
  30878. },
  30879. /**
  30880. * Sets the current layer to the given index.
  30881. *
  30882. * @method Phaser.Tilemap#setLayer
  30883. * @param {number} layer - Sets the current layer to the given index.
  30884. */
  30885. setLayer: function (layer) {
  30886. if (this.layers[layer])
  30887. {
  30888. this.currentLayer = layer;
  30889. }
  30890. },
  30891. /**
  30892. * Puts a tile of the given index value at the coordinate specified.
  30893. * @method Phaser.Tilemap#putTile
  30894. * @param {number} index - The index of this tile to set.
  30895. * @param {number} x - X position to place the tile (given in tile units, not pixels)
  30896. * @param {number} y - Y position to place the tile (given in tile units, not pixels)
  30897. * @param {number} [layer] - The Tilemap Layer to operate on.
  30898. */
  30899. putTile: function (index, x, y, layer) {
  30900. if (typeof layer === "undefined") { layer = this.currentLayer; }
  30901. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  30902. {
  30903. this.layers[layer].data[y][x] = index;
  30904. }
  30905. this.dirty = true;
  30906. },
  30907. /**
  30908. * Gets a tile from the Tilemap Layer. The coordinates are given in tile values.
  30909. * @method Phaser.Tilemap#getTile
  30910. * @param {number} x - X position to get the tile from (given in tile units, not pixels)
  30911. * @param {number} y - Y position to get the tile from (given in tile units, not pixels)
  30912. * @param {number} [layer] - The Tilemap Layer to operate on.
  30913. * @return {number} The index of the tile at the given coordinates.
  30914. */
  30915. getTile: function (x, y, layer) {
  30916. if (typeof layer === "undefined") { layer = this.currentLayer; }
  30917. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  30918. {
  30919. return this.layers[layer].data[y][x];
  30920. }
  30921. },
  30922. /**
  30923. * Gets a tile from the Tilemap layer. The coordinates are given in pixel values.
  30924. * @method Phaser.Tilemap#getTileWorldXY
  30925. * @param {number} x - X position to get the tile from (given in pixels)
  30926. * @param {number} y - Y position to get the tile from (given in pixels)
  30927. * @param {number} [layer] - The Tilemap Layer to operate on.
  30928. * @return {number} The index of the tile at the given coordinates.
  30929. */
  30930. getTileWorldXY: function (x, y, tileWidth, tileHeight, layer) {
  30931. if (typeof layer === "undefined") { layer = this.currentLayer; }
  30932. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  30933. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  30934. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  30935. {
  30936. return this.layers[layer].data[y][x];
  30937. }
  30938. },
  30939. /**
  30940. * Puts a tile into the Tilemap layer. The coordinates are given in pixel values.
  30941. * @method Phaser.Tilemap#putTileWorldXY
  30942. * @param {number} index - The index of the tile to put into the layer.
  30943. * @param {number} x - X position to insert the tile (given in pixels)
  30944. * @param {number} y - Y position to insert the tile (given in pixels)
  30945. * @param {number} tileWidth - The width of the tile in pixels.
  30946. * @param {number} tileHeight - The height of the tile in pixels.
  30947. * @param {number} [layer] - The Tilemap Layer to operate on.
  30948. */
  30949. putTileWorldXY: function (index, x, y, tileWidth, tileHeight, layer) {
  30950. if (typeof layer === "undefined") { layer = this.currentLayer; }
  30951. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  30952. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  30953. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  30954. {
  30955. this.layers[layer].data[y][x] = index;
  30956. }
  30957. this.dirty = true;
  30958. },
  30959. /**
  30960. * Copies all of the tiles in the given rectangular block into the tilemap data buffer.
  30961. * @method Phaser.Tilemap#copy
  30962. * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels)
  30963. * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels)
  30964. * @param {number} width - The width of the area to copy (given in tiles, not pixels)
  30965. * @param {number} height - The height of the area to copy (given in tiles, not pixels)
  30966. * @param {number} [layer] - The Tilemap Layer to operate on.
  30967. * @return {array} An array of the tiles that were copied.
  30968. */
  30969. copy: function (x, y, width, height, layer) {
  30970. if (typeof layer === "undefined") { layer = this.currentLayer; }
  30971. if (!this.layers[layer])
  30972. {
  30973. this._results.length = 0;
  30974. return;
  30975. }
  30976. if (typeof x === "undefined") { x = 0; }
  30977. if (typeof y === "undefined") { y = 0; }
  30978. if (typeof width === "undefined") { width = this.layers[layer].width; }
  30979. if (typeof height === "undefined") { height = this.layers[layer].height; }
  30980. if (x < 0)
  30981. {
  30982. x = 0;
  30983. }
  30984. if (y < 0)
  30985. {
  30986. y = 0;
  30987. }
  30988. if (width > this.layers[layer].width)
  30989. {
  30990. width = this.layers[layer].width;
  30991. }
  30992. if (height > this.layers[layer].height)
  30993. {
  30994. height = this.layers[layer].height;
  30995. }
  30996. this._results.length = 0;
  30997. this._results.push( { x: x, y: y, width: width, height: height, layer: layer });
  30998. for (var ty = y; ty < y + height; ty++)
  30999. {
  31000. for (var tx = x; tx < x + width; tx++)
  31001. {
  31002. this._results.push({ x: tx, y: ty, index: this.layers[layer].data[ty][tx] });
  31003. }
  31004. }
  31005. return this._results;
  31006. },
  31007. /**
  31008. * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy.
  31009. * @method Phaser.Tilemap#paste
  31010. * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels)
  31011. * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels)
  31012. * @param {array} tileblock - The block of tiles to paste.
  31013. * @param {number} layer - The Tilemap Layer to operate on.
  31014. */
  31015. paste: function (x, y, tileblock, layer) {
  31016. if (typeof x === "undefined") { x = 0; }
  31017. if (typeof y === "undefined") { y = 0; }
  31018. if (typeof layer === "undefined") { layer = this.currentLayer; }
  31019. if (!tileblock || tileblock.length < 2)
  31020. {
  31021. return;
  31022. }
  31023. // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste
  31024. var diffX = tileblock[1].x - x;
  31025. var diffY = tileblock[1].y - y;
  31026. for (var i = 1; i < tileblock.length; i++)
  31027. {
  31028. this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ] = tileblock[i].index;
  31029. }
  31030. this.dirty = true;
  31031. },
  31032. /**
  31033. * Swap tiles with 2 kinds of indexes.
  31034. * @method Phaser.Tilemap#swapTile
  31035. * @param {number} tileA - First tile index.
  31036. * @param {number} tileB - Second tile index.
  31037. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  31038. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  31039. * @param {number} width - The width in tiles of the area to operate on.
  31040. * @param {number} height - The height in tiles of the area to operate on.
  31041. */
  31042. swap: function (tileA, tileB, x, y, width, height, layer) {
  31043. this.copy(x, y, width, height, layer);
  31044. if (this._results.length < 2)
  31045. {
  31046. return;
  31047. }
  31048. this._tempA = tileA;
  31049. this._tempB = tileB;
  31050. this._results.forEach(this.swapHandler, this);
  31051. this.paste(x, y, this._results);
  31052. },
  31053. /**
  31054. * Internal function that handles the swapping of tiles.
  31055. * @method Phaser.Tilemap#swapHandler
  31056. * @param {number} value
  31057. * @param {number} index
  31058. */
  31059. swapHandler: function (value, index) {
  31060. if (value.index === this._tempA)
  31061. {
  31062. this._results[index].index = this._tempB;
  31063. }
  31064. else if (value.index === this._tempB)
  31065. {
  31066. this._results[index].index = this._tempA;
  31067. }
  31068. },
  31069. /**
  31070. * For each tile in the given area (defined by x/y and width/height) run the given callback.
  31071. * @method Phaser.Tilemap#forEach
  31072. * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter.
  31073. * @param {number} context - The context under which the callback should be run.
  31074. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  31075. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  31076. * @param {number} width - The width in tiles of the area to operate on.
  31077. * @param {number} height - The height in tiles of the area to operate on.
  31078. * @param {number} [layer] - The Tilemap Layer to operate on.
  31079. */
  31080. forEach: function (callback, context, x, y, width, height, layer) {
  31081. this.copy(x, y, width, height, layer);
  31082. if (this._results.length < 2)
  31083. {
  31084. return;
  31085. }
  31086. this._results.forEach(callback, context);
  31087. this.paste(x, y, this._results);
  31088. },
  31089. /**
  31090. * Replaces one type of tile with another in the given area (defined by x/y and width/height).
  31091. * @method Phaser.Tilemap#replace
  31092. * @param {number} tileA - First tile index.
  31093. * @param {number} tileB - Second tile index.
  31094. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  31095. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  31096. * @param {number} width - The width in tiles of the area to operate on.
  31097. * @param {number} height - The height in tiles of the area to operate on.
  31098. * @param {number} [layer] - The Tilemap Layer to operate on.
  31099. */
  31100. replace: function (tileA, tileB, x, y, width, height, layer) {
  31101. this.copy(x, y, width, height, layer);
  31102. if (this._results.length < 2)
  31103. {
  31104. return;
  31105. }
  31106. for (var i = 1; i < this._results.length; i++)
  31107. {
  31108. if (this._results[i].index === tileA)
  31109. {
  31110. this._results[i].index = tileB;
  31111. }
  31112. }
  31113. this.paste(x, y, this._results);
  31114. },
  31115. /**
  31116. * Randomises a set of tiles in a given area.
  31117. * @method Phaser.Tilemap#random
  31118. * @param {number} tileA - First tile index.
  31119. * @param {number} tileB - Second tile index.
  31120. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  31121. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  31122. * @param {number} width - The width in tiles of the area to operate on.
  31123. * @param {number} height - The height in tiles of the area to operate on.
  31124. * @param {number} [layer] - The Tilemap Layer to operate on.
  31125. */
  31126. random: function (x, y, width, height, layer) {
  31127. if (typeof layer === "undefined") { layer = this.currentLayer; }
  31128. this.copy(x, y, width, height, layer);
  31129. if (this._results.length < 2)
  31130. {
  31131. return;
  31132. }
  31133. var indexes = [];
  31134. for (var t = 1; t < this._results.length; t++)
  31135. {
  31136. var idx = this._results[t].index;
  31137. if (indexes.indexOf(idx) === -1)
  31138. {
  31139. indexes.push(idx);
  31140. }
  31141. }
  31142. for (var i = 1; i < this._results.length; i++)
  31143. {
  31144. this._results[i].index = this.game.rnd.pick(indexes);
  31145. }
  31146. this.paste(x, y, this._results);
  31147. },
  31148. /**
  31149. * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed!
  31150. * @method Phaser.Tilemap#shuffle
  31151. * @param {number} tileA - First tile index.
  31152. * @param {number} tileB - Second tile index.
  31153. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  31154. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  31155. * @param {number} width - The width in tiles of the area to operate on.
  31156. * @param {number} height - The height in tiles of the area to operate on.
  31157. * @param {number} [layer] - The Tilemap Layer to operate on.
  31158. */
  31159. shuffle: function (x, y, width, height, layer) {
  31160. if (typeof layer === "undefined") { layer = this.currentLayer; }
  31161. this.copy(x, y, width, height, layer);
  31162. if (this._results.length < 2)
  31163. {
  31164. return;
  31165. }
  31166. var header = this._results.shift();
  31167. Phaser.Utils.shuffle(this._results);
  31168. this._results.unshift(header);
  31169. this.paste(x, y, this._results);
  31170. },
  31171. /**
  31172. * Fill a block with a specific tile index.
  31173. * @method Phaser.Tilemap#fill
  31174. * @param {number} index - Index of tiles you want to fill with.
  31175. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  31176. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  31177. * @param {number} width - The width in tiles of the area to operate on.
  31178. * @param {number} height - The height in tiles of the area to operate on.
  31179. * @param {number} [layer] - The Tilemap Layer to operate on.
  31180. */
  31181. fill: function (index, x, y, width, height, layer) {
  31182. this.copy(x, y, width, height, layer);
  31183. if (this._results.length < 2)
  31184. {
  31185. return;
  31186. }
  31187. for (var i = 1; i < this._results.length; i++)
  31188. {
  31189. this._results[i].index = index;
  31190. }
  31191. this.paste(x, y, this._results);
  31192. },
  31193. /**
  31194. * Removes all layers from this tile map.
  31195. * @method Phaser.Tilemap#removeAllLayers
  31196. */
  31197. removeAllLayers: function () {
  31198. this.layers.length = 0;
  31199. this.currentLayer = 0;
  31200. },
  31201. /**
  31202. * Dumps the tilemap data out to the console.
  31203. * @method Phaser.Tilemap#dump
  31204. */
  31205. dump: function () {
  31206. var txt = '';
  31207. var args = [''];
  31208. for (var y = 0; y < this.layers[this.currentLayer].height; y++)
  31209. {
  31210. for (var x = 0; x < this.layers[this.currentLayer].width; x++)
  31211. {
  31212. txt += "%c ";
  31213. if (this.layers[this.currentLayer].data[y][x] > 1)
  31214. {
  31215. if (this.debugMap[this.layers[this.currentLayer].data[y][x]])
  31216. {
  31217. args.push("background: " + this.debugMap[this.layers[this.currentLayer].data[y][x]]);
  31218. }
  31219. else
  31220. {
  31221. args.push("background: #ffffff");
  31222. }
  31223. }
  31224. else
  31225. {
  31226. args.push("background: rgb(0, 0, 0)");
  31227. }
  31228. }
  31229. txt += "\n";
  31230. }
  31231. args[0] = txt;
  31232. console.log.apply(console, args);
  31233. },
  31234. /**
  31235. * Removes all layers from this tile map and nulls the game reference.
  31236. * @method Phaser.Tilemap#destroy
  31237. */
  31238. destroy: function () {
  31239. this.removeAllLayers();
  31240. this.game = null;
  31241. }
  31242. };
  31243. /**
  31244. * @author Richard Davey <rich@photonstorm.com>
  31245. * @copyright 2013 Photon Storm Ltd.
  31246. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  31247. */
  31248. /**
  31249. * A Tilemap Layer is a set of map data combined with a Tileset in order to render that data to the game.
  31250. *
  31251. * @class Phaser.TilemapLayer
  31252. * @constructor
  31253. * @param {Phaser.Game} game - Game reference to the currently running game.
  31254. * @param {number} x - The x coordinate of this layer.
  31255. * @param {number} y - The y coordinate of this layer.
  31256. * @param {number} renderWidth - Width of the layer.
  31257. * @param {number} renderHeight - Height of the layer.
  31258. * @param {Phaser.Tileset|string} tileset - The tile set used for rendering.
  31259. * @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs.
  31260. * @param {number} layer - The layer index within the map.
  31261. */
  31262. Phaser.TilemapLayer = function (game, x, y, renderWidth, renderHeight, tileset, tilemap, layer) {
  31263. /**
  31264. * @property {Phaser.Game} game - A reference to the currently running Game.
  31265. */
  31266. this.game = game;
  31267. /**
  31268. * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws.
  31269. */
  31270. this.canvas = Phaser.Canvas.create(renderWidth, renderHeight);
  31271. /**
  31272. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  31273. */
  31274. this.context = this.canvas.getContext('2d');
  31275. /**
  31276. * @property {PIXI.BaseTexture} baseTexture - Required Pixi var.
  31277. */
  31278. this.baseTexture = new PIXI.BaseTexture(this.canvas);
  31279. /**
  31280. * @property {PIXI.Texture} texture - Required Pixi var.
  31281. */
  31282. this.texture = new PIXI.Texture(this.baseTexture);
  31283. /**
  31284. * @property {Phaser.Frame} textureFrame - Dimensions of the renderable area.
  31285. */
  31286. this.textureFrame = new Phaser.Frame(0, 0, 0, renderWidth, renderHeight, 'tilemaplayer', game.rnd.uuid());
  31287. Phaser.Sprite.call(this, this.game, x, y, this.texture, this.textureFrame);
  31288. /**
  31289. * @property {number} type - The const type of this object.
  31290. * @default
  31291. */
  31292. this.type = Phaser.TILEMAPLAYER;
  31293. /**
  31294. * A layer that is fixed to the camera ignores the position of any ancestors in the display list and uses its x/y coordinates as offsets from the top left of the camera.
  31295. * @property {boolean} fixedToCamera - Fixes this layer to the Camera.
  31296. * @default
  31297. */
  31298. this.fixedToCamera = true;
  31299. /**
  31300. * @property {Phaser.Tileset} tileset - The tile set used for rendering.
  31301. */
  31302. this.tileset = null;
  31303. /**
  31304. * @property {number} tileWidth - The width of a single tile in pixels.
  31305. */
  31306. this.tileWidth = 0;
  31307. /**
  31308. * @property {number} tileHeight - The height of a single tile in pixels.
  31309. */
  31310. this.tileHeight = 0;
  31311. /**
  31312. * @property {number} tileMargin - The margin around the tiles.
  31313. */
  31314. this.tileMargin = 0;
  31315. /**
  31316. * @property {number} tileSpacing - The spacing around the tiles.
  31317. */
  31318. this.tileSpacing = 0;
  31319. /**
  31320. * @property {number} widthInPixels - Do NOT recommend changing after the map is loaded!
  31321. * @readonly
  31322. */
  31323. this.widthInPixels = 0;
  31324. /**
  31325. * @property {number} heightInPixels - Do NOT recommend changing after the map is loaded!
  31326. * @readonly
  31327. */
  31328. this.heightInPixels = 0;
  31329. /**
  31330. * @property {number} renderWidth - The width of the area being rendered.
  31331. */
  31332. this.renderWidth = renderWidth;
  31333. /**
  31334. * @property {number} renderHeight - The height of the area being rendered.
  31335. */
  31336. this.renderHeight = renderHeight;
  31337. /**
  31338. * @property {number} _ga - Local render loop var to help avoid gc spikes.
  31339. * @private
  31340. */
  31341. this._ga = 1;
  31342. /**
  31343. * @property {number} _dx - Local render loop var to help avoid gc spikes.
  31344. * @private
  31345. */
  31346. this._dx = 0;
  31347. /**
  31348. * @property {number} _dy - Local render loop var to help avoid gc spikes.
  31349. * @private
  31350. */
  31351. this._dy = 0;
  31352. /**
  31353. * @property {number} _dw - Local render loop var to help avoid gc spikes.
  31354. * @private
  31355. */
  31356. this._dw = 0;
  31357. /**
  31358. * @property {number} _dh - Local render loop var to help avoid gc spikes.
  31359. * @private
  31360. */
  31361. this._dh = 0;
  31362. /**
  31363. * @property {number} _tx - Local render loop var to help avoid gc spikes.
  31364. * @private
  31365. */
  31366. this._tx = 0;
  31367. /**
  31368. * @property {number} _ty - Local render loop var to help avoid gc spikes.
  31369. * @private
  31370. */
  31371. this._ty = 0;
  31372. /**
  31373. * @property {number} _tw - Local render loop var to help avoid gc spikes.
  31374. * @private
  31375. */
  31376. this._tw = 0;
  31377. /**
  31378. * @property {number} _th - Local render loop var to help avoid gc spikes.
  31379. * @private
  31380. */
  31381. this._th = 0;
  31382. /**
  31383. * @property {number} _tl - Local render loop var to help avoid gc spikes.
  31384. * @private
  31385. */
  31386. this._tl = 0;
  31387. /**
  31388. * @property {number} _maxX - Local render loop var to help avoid gc spikes.
  31389. * @private
  31390. */
  31391. this._maxX = 0;
  31392. /**
  31393. * @property {number} _maxY - Local render loop var to help avoid gc spikes.
  31394. * @private
  31395. */
  31396. this._maxY = 0;
  31397. /**
  31398. * @property {number} _startX - Local render loop var to help avoid gc spikes.
  31399. * @private
  31400. */
  31401. this._startX = 0;
  31402. /**
  31403. * @property {number} _startY - Local render loop var to help avoid gc spikes.
  31404. * @private
  31405. */
  31406. this._startY = 0;
  31407. /**
  31408. * @property {array} _results - Local render loop var to help avoid gc spikes.
  31409. * @private
  31410. */
  31411. this._results = [];
  31412. /**
  31413. * @property {number} _x - Private var.
  31414. * @private
  31415. */
  31416. this._x = 0;
  31417. /**
  31418. * @property {number} _y - Private var.
  31419. * @private
  31420. */
  31421. this._y = 0;
  31422. /**
  31423. * @property {number} _prevX - Private var.
  31424. * @private
  31425. */
  31426. this._prevX = 0;
  31427. /**
  31428. * @property {number} _prevY - Private var.
  31429. * @private
  31430. */
  31431. this._prevY = 0;
  31432. /**
  31433. * @property {number} scrollFactorX - speed at which this layer scrolls
  31434. * horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls
  31435. * half as quickly as the 'normal' camera-locked layers do)
  31436. * @default 1
  31437. */
  31438. this.scrollFactorX = 1;
  31439. /**
  31440. * @property {number} scrollFactorY - speed at which this layer scrolls
  31441. * vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls
  31442. * half as quickly as the 'normal' camera-locked layers do)
  31443. * @default 1
  31444. */
  31445. this.scrollFactorY = 1;
  31446. /**
  31447. * @property {Phaser.Tilemap} tilemap - The Tilemap to which this layer is bound.
  31448. */
  31449. this.tilemap = null;
  31450. /**
  31451. * @property {number} layer - Tilemap layer index.
  31452. */
  31453. this.layer = null;
  31454. /**
  31455. * @property {number} index
  31456. */
  31457. this.index = 0;
  31458. /**
  31459. * @property {boolean} dirty - Flag controlling when to re-render the layer.
  31460. */
  31461. this.dirty = true;
  31462. if (tileset instanceof Phaser.Tileset || typeof tileset === 'string')
  31463. {
  31464. this.updateTileset(tileset);
  31465. }
  31466. if (tilemap instanceof Phaser.Tilemap)
  31467. {
  31468. this.updateMapData(tilemap, layer);
  31469. }
  31470. };
  31471. Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype);
  31472. Phaser.TilemapLayer.prototype = Phaser.Utils.extend(true, Phaser.TilemapLayer.prototype, Phaser.Sprite.prototype, PIXI.Sprite.prototype);
  31473. Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer;
  31474. /**
  31475. * Automatically called by World.preUpdate. Handles cache updates.
  31476. *
  31477. * @method Phaser.TilemapLayer#update
  31478. * @memberof Phaser.TilemapLayer
  31479. */
  31480. Phaser.TilemapLayer.prototype.update = function () {
  31481. this.scrollX = this.game.camera.x * this.scrollFactorX;
  31482. this.scrollY = this.game.camera.y * this.scrollFactorY;
  31483. this.render();
  31484. }
  31485. /**
  31486. * Sets the world size to match the size of this layer.
  31487. *
  31488. * @method Phaser.TilemapLayer#resizeWorld
  31489. * @memberof Phaser.TilemapLayer
  31490. */
  31491. Phaser.TilemapLayer.prototype.resizeWorld = function () {
  31492. this.game.world.setBounds(0, 0, this.widthInPixels, this.heightInPixels);
  31493. }
  31494. /**
  31495. * Updates the Tileset data.
  31496. *
  31497. * @method Phaser.TilemapLayer#updateTileset
  31498. * @memberof Phaser.TilemapLayer
  31499. * @param {Phaser.Tileset|string} tileset - The tileset to use for this layer.
  31500. */
  31501. Phaser.TilemapLayer.prototype.updateTileset = function (tileset) {
  31502. if (tileset instanceof Phaser.Tileset)
  31503. {
  31504. this.tileset = tileset;
  31505. }
  31506. else if (typeof tileset === 'string')
  31507. {
  31508. this.tileset = this.game.cache.getTileset('tiles');
  31509. }
  31510. else
  31511. {
  31512. return;
  31513. }
  31514. this.tileWidth = this.tileset.tileWidth;
  31515. this.tileHeight = this.tileset.tileHeight;
  31516. this.tileMargin = this.tileset.tileMargin;
  31517. this.tileSpacing = this.tileset.tileSpacing;
  31518. this.updateMax();
  31519. }
  31520. /**
  31521. * Updates the Tilemap data.
  31522. *
  31523. * @method Phaser.TilemapLayer#updateMapData
  31524. * @memberof Phaser.TilemapLayer
  31525. * @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs.
  31526. * @param {number} layer - The layer index within the map.
  31527. */
  31528. Phaser.TilemapLayer.prototype.updateMapData = function (tilemap, layer) {
  31529. if (typeof layer === 'undefined')
  31530. {
  31531. layer = 0;
  31532. }
  31533. if (tilemap instanceof Phaser.Tilemap)
  31534. {
  31535. this.tilemap = tilemap;
  31536. this.layer = this.tilemap.layers[layer];
  31537. this.index = layer;
  31538. this.updateMax();
  31539. this.tilemap.dirty = true;
  31540. }
  31541. }
  31542. /**
  31543. * Take an x coordinate that doesn't account for scrollFactorY and 'fix' it
  31544. * into a scrolled local space. Used primarily internally
  31545. * @method Phaser.TilemapLayer#_fixX
  31546. * @memberof Phaser.TilemapLayer
  31547. * @private
  31548. * @param {number} x - x coordinate in camera space
  31549. * @return {number} x coordinate in scrollFactor-adjusted dimensions
  31550. */
  31551. Phaser.TilemapLayer.prototype._fixX = function(x) {
  31552. if (this.scrollFactorX === 1)
  31553. {
  31554. return x;
  31555. }
  31556. var leftEdge = x - (this._x / this.scrollFactorX);
  31557. return this._x + leftEdge;
  31558. }
  31559. /**
  31560. * Take an x coordinate that _does_ account for scrollFactorY and 'unfix' it
  31561. * back to camera space. Used primarily internally
  31562. * @method Phaser.TilemapLayer#_unfixX
  31563. * @memberof Phaser.TilemapLayer
  31564. * @private
  31565. * @param {number} x - x coordinate in scrollFactor-adjusted dimensions
  31566. * @return {number} x coordinate in camera space
  31567. */
  31568. Phaser.TilemapLayer.prototype._unfixX = function(x) {
  31569. if (this.scrollFactorX === 1)
  31570. {
  31571. return x;
  31572. }
  31573. var leftEdge = x - this._x;
  31574. return (this._x / this.scrollFactorX) + leftEdge;
  31575. }
  31576. /**
  31577. * Take a y coordinate that doesn't account for scrollFactorY and 'fix' it
  31578. * into a scrolled local space. Used primarily internally
  31579. * @method Phaser.TilemapLayer#_fixY
  31580. * @memberof Phaser.TilemapLayer
  31581. * @private
  31582. * @param {number} y - y coordinate in camera space
  31583. * @return {number} y coordinate in scrollFactor-adjusted dimensions
  31584. */
  31585. Phaser.TilemapLayer.prototype._fixY = function(y) {
  31586. if (this.scrollFactorY === 1)
  31587. {
  31588. return y;
  31589. }
  31590. var topEdge = y - (this._y / this.scrollFactorY);
  31591. return this._y + topEdge;
  31592. }
  31593. /**
  31594. * Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it
  31595. * back to camera space. Used primarily internally
  31596. * @method Phaser.TilemapLayer#_unfixY
  31597. * @memberof Phaser.TilemapLayer
  31598. * @private
  31599. * @param {number} y - y coordinate in scrollFactor-adjusted dimensions
  31600. * @return {number} y coordinate in camera space
  31601. */
  31602. Phaser.TilemapLayer.prototype._unfixY = function(y) {
  31603. if (this.scrollFactorY === 1)
  31604. {
  31605. return y;
  31606. }
  31607. var topEdge = y - this._y;
  31608. return (this._y / this.scrollFactorY) + topEdge;
  31609. }
  31610. /**
  31611. * Convert a pixel value to a tile coordinate.
  31612. * @method Phaser.TilemapLayer#getTileX
  31613. * @memberof Phaser.TilemapLayer
  31614. * @param {number} x - X position of the point in target tile.
  31615. * @return {Phaser.Tile} The tile with specific properties.
  31616. */
  31617. Phaser.TilemapLayer.prototype.getTileX = function (x) {
  31618. var tileWidth = this.tileWidth * this.scale.x;
  31619. return this.game.math.snapToFloor(this._fixX(x), tileWidth) / tileWidth;
  31620. }
  31621. /**
  31622. * Convert a pixel value to a tile coordinate.
  31623. * @method Phaser.TilemapLayer#getTileY
  31624. * @memberof Phaser.TilemapLayer
  31625. * @param {number} y - Y position of the point in target tile.
  31626. * @return {Phaser.Tile} The tile with specific properties.
  31627. */
  31628. Phaser.TilemapLayer.prototype.getTileY = function (y) {
  31629. var tileHeight = this.tileHeight * this.scale.y;
  31630. return this.game.math.snapToFloor(this._fixY(y), tileHeight) / tileHeight;
  31631. }
  31632. /**
  31633. * Convert a pixel value to a tile coordinate.
  31634. * @method Phaser.TilemapLayer#getTileXY
  31635. * @memberof Phaser.TilemapLayer
  31636. * @param {number} x - X position of the point in target tile.
  31637. * @param {number} y - Y position of the point in target tile.
  31638. * @return {Phaser.Tile} The tile with specific properties.
  31639. */
  31640. Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) {
  31641. point.x = this.getTileX(x);
  31642. point.y = this.getTileY(y);
  31643. return point;
  31644. }
  31645. /**
  31646. * Get the tiles within the given area.
  31647. * @method Phaser.TilemapLayer#getTiles
  31648. * @memberof Phaser.TilemapLayer
  31649. * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels)
  31650. * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels)
  31651. * @param {number} width - The width of the area to copy (given in tiles, not pixels)
  31652. * @param {number} height - The height of the area to copy (given in tiles, not pixels)
  31653. * @param {boolean} collides - If true only return tiles that collide on one or more faces.
  31654. * @return {array} Array with tiles informations (each contains x, y, and the tile).
  31655. */
  31656. Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides) {
  31657. if (this.tilemap === null)
  31658. {
  31659. return;
  31660. }
  31661. // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all)
  31662. if (typeof collides === 'undefined') { collides = false; }
  31663. // Cap the values
  31664. if (x < 0)
  31665. {
  31666. x = 0;
  31667. }
  31668. if (y < 0)
  31669. {
  31670. y = 0;
  31671. }
  31672. // adjust the x,y coordinates for scrollFactor
  31673. x = this._fixX( x );
  31674. y = this._fixY( y );
  31675. if (width > this.widthInPixels)
  31676. {
  31677. width = this.widthInPixels;
  31678. }
  31679. if (height > this.heightInPixels)
  31680. {
  31681. height = this.heightInPixels;
  31682. }
  31683. var tileWidth = this.tileWidth * this.scale.x;
  31684. var tileHeight = this.tileHeight * this.scale.y;
  31685. // Convert the pixel values into tile coordinates
  31686. this._tx = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  31687. this._ty = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  31688. this._tw = (this.game.math.snapToCeil(width, tileWidth) + tileWidth) / tileWidth;
  31689. this._th = (this.game.math.snapToCeil(height, tileHeight) + tileHeight) / tileHeight;
  31690. // This should apply the layer x/y here
  31691. // this._results.length = 0;
  31692. this._results = [];
  31693. // pretty sure we don't use this any more?
  31694. // this._results.push( { x: x, y: y, width: width, height: height, tx: this._tx, ty: this._ty, tw: this._tw, th: this._th });
  31695. var _index = 0;
  31696. var _tile = null;
  31697. var sx = 0;
  31698. var sy = 0;
  31699. for (var wy = this._ty; wy < this._ty + this._th; wy++)
  31700. {
  31701. for (var wx = this._tx; wx < this._tx + this._tw; wx++)
  31702. {
  31703. if (this.layer.data[wy] && this.layer.data[wy][wx])
  31704. {
  31705. // Could combine
  31706. _index = this.layer.data[wy][wx] - 1;
  31707. _tile = this.tileset.getTile(_index);
  31708. sx = _tile.width * this.scale.x;
  31709. sy = _tile.height * this.scale.y;
  31710. if (collides === false || (collides && _tile.collideNone === false))
  31711. {
  31712. // convert tile coordinates back to camera space for return
  31713. var _wx = this._unfixX( wx*sx ) / tileWidth;
  31714. var _wy = this._unfixY( wy*sy ) / tileHeight;
  31715. this._results.push({ x: _wx * sx, right: (_wx * sx) + sx, y: _wy * sy, bottom: (_wy * sy) + sy, width: sx, height: sy, tx: _wx, ty: _wy, tile: _tile });
  31716. }
  31717. }
  31718. }
  31719. }
  31720. return this._results;
  31721. }
  31722. /**
  31723. * Internal function to update maximum values.
  31724. * @method Phaser.TilemapLayer#updateMax
  31725. * @memberof Phaser.TilemapLayer
  31726. */
  31727. Phaser.TilemapLayer.prototype.updateMax = function () {
  31728. this._maxX = this.game.math.ceil(this.canvas.width / this.tileWidth) + 1;
  31729. this._maxY = this.game.math.ceil(this.canvas.height / this.tileHeight) + 1;
  31730. if (this.layer)
  31731. {
  31732. if (this._maxX > this.layer.width)
  31733. {
  31734. this._maxX = this.layer.width;
  31735. }
  31736. if (this._maxY > this.layer.height)
  31737. {
  31738. this._maxY = this.layer.height;
  31739. }
  31740. this.widthInPixels = this.layer.width * this.tileWidth;
  31741. this.heightInPixels = this.layer.height * this.tileHeight;
  31742. }
  31743. this.dirty = true;
  31744. }
  31745. /**
  31746. * Renders the tiles to the layer canvas and pushes to the display.
  31747. * @method Phaser.TilemapLayer#render
  31748. * @memberof Phaser.TilemapLayer
  31749. */
  31750. Phaser.TilemapLayer.prototype.render = function () {
  31751. if (this.tilemap && this.tilemap.dirty)
  31752. {
  31753. this.dirty = true;
  31754. }
  31755. if (!this.dirty || !this.tileset || !this.tilemap || !this.visible)
  31756. {
  31757. return;
  31758. }
  31759. this._prevX = this._dx;
  31760. this._prevY = this._dy;
  31761. this._dx = -(this._x - (this._startX * this.tileWidth));
  31762. this._dy = -(this._y - (this._startY * this.tileHeight));
  31763. this._tx = this._dx;
  31764. this._ty = this._dy;
  31765. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  31766. for (var y = this._startY; y < this._startY + this._maxY; y++)
  31767. {
  31768. this._column = this.layer.data[y];
  31769. for (var x = this._startX; x < this._startX + this._maxX; x++)
  31770. {
  31771. // only -1 on TILED maps, not CSV
  31772. var tile = this.tileset.tiles[this._column[x]-1];
  31773. if (tile)
  31774. {
  31775. this.context.drawImage(
  31776. this.tileset.image,
  31777. tile.x,
  31778. tile.y,
  31779. this.tileWidth,
  31780. this.tileHeight,
  31781. Math.floor(this._tx),
  31782. Math.floor(this._ty),
  31783. this.tileWidth,
  31784. this.tileHeight
  31785. );
  31786. }
  31787. this._tx += this.tileWidth;
  31788. }
  31789. this._tx = this._dx;
  31790. this._ty += this.tileHeight;
  31791. }
  31792. // Only needed if running in WebGL, otherwise this array will never get cleared down I don't think!
  31793. if (this.game.renderType == Phaser.WEBGL)
  31794. {
  31795. PIXI.texturesToUpdate.push(this.baseTexture);
  31796. }
  31797. this.dirty = false;
  31798. if (this.tilemap.dirty)
  31799. {
  31800. this.tilemap.dirty = false;
  31801. }
  31802. return true;
  31803. }
  31804. /**
  31805. * Returns the absolute delta x value.
  31806. * @method Phaser.TilemapLayer#deltaAbsX
  31807. * @memberof Phaser.TilemapLayer
  31808. * @return {number} Absolute delta X value
  31809. */
  31810. Phaser.TilemapLayer.prototype.deltaAbsX = function () {
  31811. return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX());
  31812. }
  31813. /**
  31814. * Returns the absolute delta y value.
  31815. * @method Phaser.TilemapLayer#deltaAbsY
  31816. * @memberof Phaser.TilemapLayer
  31817. * @return {number} Absolute delta Y value
  31818. */
  31819. Phaser.TilemapLayer.prototype.deltaAbsY = function () {
  31820. return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY());
  31821. }
  31822. /**
  31823. * Returns the delta x value.
  31824. * @method Phaser.TilemapLayer#deltaX
  31825. * @memberof Phaser.TilemapLayer
  31826. * @return {number} Delta X value
  31827. */
  31828. Phaser.TilemapLayer.prototype.deltaX = function () {
  31829. return this._dx - this._prevX;
  31830. }
  31831. /**
  31832. * Returns the delta y value.
  31833. * @method Phaser.TilemapLayer#deltaY
  31834. * @memberof Phaser.TilemapLayer
  31835. * @return {number} Delta Y value
  31836. */
  31837. Phaser.TilemapLayer.prototype.deltaY = function () {
  31838. return this._dy - this._prevY;
  31839. }
  31840. /**
  31841. * @name Phaser.TilemapLayer#scrollX
  31842. * @property {number} scrollX - Scrolls the map horizontally or returns the current x position.
  31843. */
  31844. Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", {
  31845. get: function () {
  31846. return this._x;
  31847. },
  31848. set: function (value) {
  31849. if (value !== this._x && value >= 0 && this.layer)
  31850. {
  31851. this._x = value;
  31852. if (this._x > (this.widthInPixels - this.renderWidth))
  31853. {
  31854. this._x = this.widthInPixels - this.renderWidth;
  31855. }
  31856. this._startX = this.game.math.floor(this._x / this.tileWidth);
  31857. if (this._startX < 0)
  31858. {
  31859. this._startX = 0;
  31860. }
  31861. if (this._startX + this._maxX > this.layer.width)
  31862. {
  31863. this._startX = this.layer.width - this._maxX;
  31864. }
  31865. this.dirty = true;
  31866. }
  31867. }
  31868. });
  31869. /**
  31870. * @name Phaser.TilemapLayer#scrollY
  31871. * @property {number} scrollY - Scrolls the map vertically or returns the current y position.
  31872. */
  31873. Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", {
  31874. get: function () {
  31875. return this._y;
  31876. },
  31877. set: function (value) {
  31878. if (value !== this._y && value >= 0 && this.layer)
  31879. {
  31880. this._y = value;
  31881. if (this._y > (this.heightInPixels - this.renderHeight))
  31882. {
  31883. this._y = this.heightInPixels - this.renderHeight;
  31884. }
  31885. this._startY = this.game.math.floor(this._y / this.tileHeight);
  31886. if (this._startY < 0)
  31887. {
  31888. this._startY = 0;
  31889. }
  31890. if (this._startY + this._maxY > this.layer.height)
  31891. {
  31892. this._startY = this.layer.height - this._maxY;
  31893. }
  31894. this.dirty = true;
  31895. }
  31896. }
  31897. });
  31898. /**
  31899. * @author Richard Davey <rich@photonstorm.com>
  31900. * @copyright 2013 Photon Storm Ltd.
  31901. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  31902. */
  31903. /**
  31904. * Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap.
  31905. *
  31906. * @class Phaser.TilemapParser
  31907. */
  31908. Phaser.TilemapParser = {
  31909. /**
  31910. * Creates a Tileset object.
  31911. * @method Phaser.TilemapParser.tileset
  31912. * @param {Phaser.Game} game - Game reference to the currently running game.
  31913. * @param {string} key
  31914. * @param {number} tileWidth
  31915. * @param {number} tileHeight
  31916. * @param {number} tileMax
  31917. * @param {number} tileMargin
  31918. * @param {number} tileSpacing
  31919. * @return {Phaser.Tileset} Generated Tileset object.
  31920. */
  31921. tileset: function (game, key, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing) {
  31922. // How big is our image?
  31923. var img = game.cache.getTilesetImage(key);
  31924. if (img == null)
  31925. {
  31926. return null;
  31927. }
  31928. var width = img.width;
  31929. var height = img.height;
  31930. // If no tile width/height is given, try and figure it out (won't work if the tileset has margin/spacing)
  31931. if (tileWidth <= 0)
  31932. {
  31933. tileWidth = Math.floor(-width / Math.min(-1, tileWidth));
  31934. }
  31935. if (tileHeight <= 0)
  31936. {
  31937. tileHeight = Math.floor(-height / Math.min(-1, tileHeight));
  31938. }
  31939. var row = Math.round(width / tileWidth);
  31940. var column = Math.round(height / tileHeight);
  31941. var total = row * column;
  31942. if (tileMax !== -1)
  31943. {
  31944. total = tileMax;
  31945. }
  31946. // Zero or smaller than tile sizes?
  31947. if (width === 0 || height === 0 || width < tileWidth || height < tileHeight || total === 0)
  31948. {
  31949. console.warn("Phaser.TilemapParser.tileSet: width/height zero or width/height < given tileWidth/tileHeight");
  31950. return null;
  31951. }
  31952. // Let's create some tiles
  31953. var x = tileMargin;
  31954. var y = tileMargin;
  31955. var tileset = new Phaser.Tileset(img, key, tileWidth, tileHeight, tileMargin, tileSpacing);
  31956. for (var i = 0; i < total; i++)
  31957. {
  31958. tileset.addTile(new Phaser.Tile(tileset, i, x, y, tileWidth, tileHeight));
  31959. x += tileWidth + tileSpacing;
  31960. if (x === width)
  31961. {
  31962. x = tileMargin;
  31963. y += tileHeight + tileSpacing;
  31964. }
  31965. }
  31966. return tileset;
  31967. },
  31968. /**
  31969. * Parse tileset data from the cache and creates a Tileset object.
  31970. * @method Phaser.TilemapParser.parse
  31971. * @param {Phaser.Game} game - Game reference to the currently running game.
  31972. * @param {object} data
  31973. * @param {string} format
  31974. * @return {Phaser.Tileset} Generated Tileset object.
  31975. */
  31976. parse: function (game, data, format) {
  31977. if (format === Phaser.Tilemap.CSV)
  31978. {
  31979. return this.parseCSV(data);
  31980. }
  31981. else if (format === Phaser.Tilemap.TILED_JSON)
  31982. {
  31983. return this.parseTiledJSON(data);
  31984. }
  31985. },
  31986. /**
  31987. * Parses a CSV file into valid map data.
  31988. * @method Phaser.TilemapParser.parseCSV
  31989. * @param {string} data - The CSV file data.
  31990. * @return {object} Generated map data.
  31991. */
  31992. parseCSV: function (data) {
  31993. // Trim any rogue whitespace from the data
  31994. data = data.trim();
  31995. var output = [];
  31996. var rows = data.split("\n");
  31997. var height = rows.length;
  31998. var width = 0;
  31999. for (var i = 0; i < rows.length; i++)
  32000. {
  32001. output[i] = [];
  32002. var column = rows[i].split(",");
  32003. for (var c = 0; c < column.length; c++)
  32004. {
  32005. output[i][c] = parseInt(column[c], 10);
  32006. }
  32007. if (width === 0)
  32008. {
  32009. width = column.length;
  32010. }
  32011. }
  32012. return [{ name: 'csv', width: width, height: height, alpha: 1, visible: true, indexes: [], tileMargin: 0, tileSpacing: 0, data: output }];
  32013. },
  32014. /**
  32015. * Parses a Tiled JSON file into valid map data.
  32016. * @method Phaser.TilemapParser.parseJSON
  32017. * @param {object} json- The Tiled JSON data.
  32018. * @return {object} Generated map data.
  32019. */
  32020. parseTiledJSON: function (json) {
  32021. var layers = [];
  32022. for (var i = 0; i < json.layers.length; i++)
  32023. {
  32024. // Check it's a data layer
  32025. if (!json.layers[i].data)
  32026. {
  32027. continue;
  32028. }
  32029. // json.tilewidth
  32030. // json.tileheight
  32031. var layer = {
  32032. name: json.layers[i].name,
  32033. width: json.layers[i].width,
  32034. height: json.layers[i].height,
  32035. alpha: json.layers[i].opacity,
  32036. visible: json.layers[i].visible,
  32037. indexes: [],
  32038. tileMargin: json.tilesets[0].margin,
  32039. tileSpacing: json.tilesets[0].spacing
  32040. };
  32041. var output = [];
  32042. var c = 0;
  32043. var row;
  32044. for (var t = 0; t < json.layers[i].data.length; t++)
  32045. {
  32046. if (c === 0)
  32047. {
  32048. row = [];
  32049. }
  32050. row.push(json.layers[i].data[t]);
  32051. c++;
  32052. if (c == json.layers[i].width)
  32053. {
  32054. output.push(row);
  32055. c = 0;
  32056. }
  32057. }
  32058. layer.data = output;
  32059. layers.push(layer);
  32060. }
  32061. return layers;
  32062. }
  32063. }
  32064. /**
  32065. * @author Richard Davey <rich@photonstorm.com>
  32066. * @copyright 2013 Photon Storm Ltd.
  32067. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  32068. */
  32069. /**
  32070. * A Tile set is a combination of an image containing the tiles and collision data per tile.
  32071. *
  32072. * @class Phaser.Tileset
  32073. * @constructor
  32074. * @param {Image} image - The Image object from the Cache.
  32075. * @param {string} key - The key of the tileset in the cache.
  32076. * @param {number} tileWidth - The width of the tile in pixels.
  32077. * @param {number} tileHeight - The height of the tile in pixels.
  32078. * @param {number} [tileMargin] - The margin around the tiles in the sheet.
  32079. * @param {number} [tileSpacing] - The spacing between the tiles in the sheet.
  32080. */
  32081. Phaser.Tileset = function (image, key, tileWidth, tileHeight, tileMargin, tileSpacing) {
  32082. if (typeof tileMargin === "undefined") { tileMargin = 0; }
  32083. if (typeof tileSpacing === "undefined") { tileSpacing = 0; }
  32084. /**
  32085. * @property {string} key - The cache ID.
  32086. */
  32087. this.key = key;
  32088. /**
  32089. * @property {object} image - The image used for rendering.
  32090. */
  32091. this.image = image;
  32092. /**
  32093. * @property {number} tileWidth - The width of a tile in pixels.
  32094. */
  32095. this.tileWidth = tileWidth;
  32096. /**
  32097. * @property {number} tileHeight - The height of a tile in pixels.
  32098. */
  32099. this.tileHeight = tileHeight;
  32100. /**
  32101. * @property {number} tileMargin - The margin around the tiles in the sheet.
  32102. */
  32103. this.margin = tileMargin;
  32104. /**
  32105. * @property {number} tileSpacing - The margin around the tiles in the sheet.
  32106. */
  32107. this.spacing = tileSpacing;
  32108. /**
  32109. * @property {array} tiles - An array of the tile collision data.
  32110. */
  32111. this.tiles = [];
  32112. }
  32113. Phaser.Tileset.prototype = {
  32114. /**
  32115. * Adds a Tile into this set.
  32116. *
  32117. * @method Phaser.Tileset#addTile
  32118. * @param {Phaser.Tile} tile - The tile to add to this set.
  32119. */
  32120. addTile: function (tile) {
  32121. this.tiles.push(tile);
  32122. return tile;
  32123. },
  32124. /**
  32125. * Gets a Tile from this set.
  32126. *
  32127. * @method Phaser.Tileset#getTile
  32128. * @param {number} index - The index of the tile within the set.
  32129. * @return {Phaser.Tile} The tile.
  32130. */
  32131. getTile: function (index) {
  32132. if (this.tiles[index])
  32133. {
  32134. return this.tiles[index];
  32135. }
  32136. return null;
  32137. },
  32138. /**
  32139. * Sets tile spacing and margins.
  32140. *
  32141. * @method Phaser.Tileset#setSpacing
  32142. * @param {number} [tileMargin] - The margin around the tiles in the sheet.
  32143. * @param {number} [tileSpacing] - The spacing between the tiles in the sheet.
  32144. */
  32145. setSpacing: function (margin, spacing) {
  32146. this.tileMargin = margin;
  32147. this.tileSpacing = spacing;
  32148. },
  32149. /**
  32150. * Checks if the tile at the given index can collide.
  32151. *
  32152. * @method Phaser.Tileset#canCollide
  32153. * @param {number} index - The index of the tile within the set.
  32154. * @return {boolean} True or false depending on the tile collision or null if no tile was found at the given index.
  32155. */
  32156. canCollide: function (index) {
  32157. if (this.tiles[index])
  32158. {
  32159. return this.tiles[index].collideNone;
  32160. }
  32161. return null;
  32162. },
  32163. /**
  32164. * Checks if the tile at the given index exists.
  32165. *
  32166. * @method Phaser.Tileset#checkTileIndex
  32167. * @param {number} index - The index of the tile within the set.
  32168. * @return {boolean} True if a tile exists at the given index otherwise false.
  32169. */
  32170. checkTileIndex: function (index) {
  32171. return (this.tiles[index]);
  32172. },
  32173. /**
  32174. * Sets collision values on a range of tiles in the set.
  32175. *
  32176. * @method Phaser.Tileset#setCollisionRange
  32177. * @param {number} start - The index to start setting the collision data on.
  32178. * @param {number} stop - The index to stop setting the collision data on.
  32179. * @param {boolean} left - Should the tile collide on the left?
  32180. * @param {boolean} right - Should the tile collide on the right?
  32181. * @param {boolean} up - Should the tile collide on the top?
  32182. * @param {boolean} down - Should the tile collide on the bottom?
  32183. */
  32184. setCollisionRange: function (start, stop, left, right, up, down) {
  32185. if (this.tiles[start] && this.tiles[stop] && start < stop)
  32186. {
  32187. for (var i = start; i <= stop; i++)
  32188. {
  32189. this.tiles[i].setCollision(left, right, up, down);
  32190. }
  32191. }
  32192. },
  32193. /**
  32194. * Sets collision values on a tile in the set.
  32195. *
  32196. * @method Phaser.Tileset#setCollision
  32197. * @param {number} index - The index of the tile within the set.
  32198. * @param {boolean} left - Should the tile collide on the left?
  32199. * @param {boolean} right - Should the tile collide on the right?
  32200. * @param {boolean} up - Should the tile collide on the top?
  32201. * @param {boolean} down - Should the tile collide on the bottom?
  32202. */
  32203. setCollision: function (index, left, right, up, down) {
  32204. if (this.tiles[index])
  32205. {
  32206. this.tiles[index].setCollision(left, right, up, down);
  32207. }
  32208. }
  32209. }
  32210. /**
  32211. * @name Phaser.Tileset#total
  32212. * @property {number} total - The total number of tiles in this Tileset.
  32213. * @readonly
  32214. */
  32215. Object.defineProperty(Phaser.Tileset.prototype, "total", {
  32216. get: function () {
  32217. return this.tiles.length;
  32218. }
  32219. });
  32220. /**
  32221. * We're replacing a couple of Pixi's methods here to fix or add some vital functionality:
  32222. *
  32223. * 1) Added support for Trimmed sprite sheets
  32224. * 2) Skip display objects with an alpha of zero
  32225. * 3) Avoid Style Recalculation from the incorrect bgcolor value
  32226. *
  32227. * Hopefully we can remove this once Pixi has been updated to support these things.
  32228. */
  32229. /**
  32230. * Renders the stage to its canvas view
  32231. *
  32232. * @method render
  32233. * @param stage {Stage} the Stage element to be rendered
  32234. */
  32235. PIXI.CanvasRenderer.prototype.render = function(stage)
  32236. {
  32237. PIXI.texturesToUpdate.length = 0;
  32238. PIXI.texturesToDestroy.length = 0;
  32239. PIXI.visibleCount++;
  32240. stage.updateTransform();
  32241. this.context.setTransform(1, 0, 0, 1, 0, 0);
  32242. this.context.clearRect(0, 0, this.width, this.height)
  32243. this.renderDisplayObject(stage);
  32244. // Remove frame updates
  32245. if (PIXI.Texture.frameUpdates.length > 0)
  32246. {
  32247. PIXI.Texture.frameUpdates.length = 0;
  32248. }
  32249. }
  32250. PIXI.CanvasRenderer.prototype.renderDisplayObject = function(displayObject)
  32251. {
  32252. // Once the display object hits this we can break the loop
  32253. var testObject = displayObject.last._iNext;
  32254. displayObject = displayObject.first;
  32255. do
  32256. {
  32257. //transform = displayObject.worldTransform;
  32258. if (!displayObject.visible)
  32259. {
  32260. displayObject = displayObject.last._iNext;
  32261. continue;
  32262. }
  32263. if (!displayObject.renderable || displayObject.alpha === 0)
  32264. {
  32265. displayObject = displayObject._iNext;
  32266. continue;
  32267. }
  32268. if (displayObject instanceof PIXI.Sprite)
  32269. {
  32270. // var frame = displayObject.texture.frame;
  32271. if (displayObject.texture.frame)
  32272. {
  32273. this.context.globalAlpha = displayObject.worldAlpha;
  32274. if (displayObject.texture.trimmed)
  32275. {
  32276. this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2] + displayObject.texture.trim.x, displayObject.worldTransform[5] + displayObject.texture.trim.y);
  32277. }
  32278. else
  32279. {
  32280. this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]);
  32281. }
  32282. this.context.drawImage(
  32283. displayObject.texture.baseTexture.source,
  32284. displayObject.texture.frame.x,
  32285. displayObject.texture.frame.y,
  32286. displayObject.texture.frame.width,
  32287. displayObject.texture.frame.height,
  32288. (displayObject.anchor.x) * -displayObject.texture.frame.width,
  32289. (displayObject.anchor.y) * -displayObject.texture.frame.height,
  32290. displayObject.texture.frame.width,
  32291. displayObject.texture.frame.height);
  32292. }
  32293. }
  32294. else if (displayObject instanceof PIXI.Strip)
  32295. {
  32296. this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5])
  32297. this.renderStrip(displayObject);
  32298. }
  32299. else if (displayObject instanceof PIXI.TilingSprite)
  32300. {
  32301. this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5])
  32302. this.renderTilingSprite(displayObject);
  32303. }
  32304. else if (displayObject instanceof PIXI.CustomRenderable)
  32305. {
  32306. displayObject.renderCanvas(this);
  32307. }
  32308. else if (displayObject instanceof PIXI.Graphics)
  32309. {
  32310. this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5])
  32311. PIXI.CanvasGraphics.renderGraphics(displayObject, this.context);
  32312. }
  32313. else if (displayObject instanceof PIXI.FilterBlock)
  32314. {
  32315. if (displayObject.open)
  32316. {
  32317. this.context.save();
  32318. var cacheAlpha = displayObject.mask.alpha;
  32319. var maskTransform = displayObject.mask.worldTransform;
  32320. this.context.setTransform(maskTransform[0], maskTransform[3], maskTransform[1], maskTransform[4], maskTransform[2], maskTransform[5])
  32321. displayObject.mask.worldAlpha = 0.5;
  32322. this.context.worldAlpha = 0;
  32323. PIXI.CanvasGraphics.renderGraphicsMask(displayObject.mask, this.context);
  32324. this.context.clip();
  32325. displayObject.mask.worldAlpha = cacheAlpha;
  32326. }
  32327. else
  32328. {
  32329. this.context.restore();
  32330. }
  32331. }
  32332. // count++
  32333. displayObject = displayObject._iNext;
  32334. }
  32335. while(displayObject != testObject)
  32336. }
  32337. PIXI.WebGLBatch.prototype.update = function()
  32338. {
  32339. // var gl = this.gl;
  32340. // var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index, index2, index3
  32341. var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index;
  32342. var a, b, c, d, tx, ty;
  32343. var indexRun = 0;
  32344. var displayObject = this.head;
  32345. while(displayObject)
  32346. {
  32347. if(displayObject.vcount === PIXI.visibleCount)
  32348. {
  32349. width = displayObject.texture.frame.width;
  32350. height = displayObject.texture.frame.height;
  32351. // TODO trim??
  32352. aX = displayObject.anchor.x;// - displayObject.texture.trim.x
  32353. aY = displayObject.anchor.y; //- displayObject.texture.trim.y
  32354. w0 = width * (1-aX);
  32355. w1 = width * -aX;
  32356. h0 = height * (1-aY);
  32357. h1 = height * -aY;
  32358. index = indexRun * 8;
  32359. worldTransform = displayObject.worldTransform;
  32360. a = worldTransform[0];
  32361. b = worldTransform[3];
  32362. c = worldTransform[1];
  32363. d = worldTransform[4];
  32364. tx = worldTransform[2];
  32365. ty = worldTransform[5];
  32366. if (displayObject.texture.trimmed)
  32367. {
  32368. tx += displayObject.texture.trim.x;
  32369. ty += displayObject.texture.trim.y;
  32370. }
  32371. this.verticies[index + 0 ] = a * w1 + c * h1 + tx;
  32372. this.verticies[index + 1 ] = d * h1 + b * w1 + ty;
  32373. this.verticies[index + 2 ] = a * w0 + c * h1 + tx;
  32374. this.verticies[index + 3 ] = d * h1 + b * w0 + ty;
  32375. this.verticies[index + 4 ] = a * w0 + c * h0 + tx;
  32376. this.verticies[index + 5 ] = d * h0 + b * w0 + ty;
  32377. this.verticies[index + 6] = a * w1 + c * h0 + tx;
  32378. this.verticies[index + 7] = d * h0 + b * w1 + ty;
  32379. if(displayObject.updateFrame || displayObject.texture.updateFrame)
  32380. {
  32381. this.dirtyUVS = true;
  32382. var texture = displayObject.texture;
  32383. var frame = texture.frame;
  32384. var tw = texture.baseTexture.width;
  32385. var th = texture.baseTexture.height;
  32386. this.uvs[index + 0] = frame.x / tw;
  32387. this.uvs[index +1] = frame.y / th;
  32388. this.uvs[index +2] = (frame.x + frame.width) / tw;
  32389. this.uvs[index +3] = frame.y / th;
  32390. this.uvs[index +4] = (frame.x + frame.width) / tw;
  32391. this.uvs[index +5] = (frame.y + frame.height) / th;
  32392. this.uvs[index +6] = frame.x / tw;
  32393. this.uvs[index +7] = (frame.y + frame.height) / th;
  32394. displayObject.updateFrame = false;
  32395. }
  32396. // TODO this probably could do with some optimisation....
  32397. if(displayObject.cacheAlpha != displayObject.worldAlpha)
  32398. {
  32399. displayObject.cacheAlpha = displayObject.worldAlpha;
  32400. var colorIndex = indexRun * 4;
  32401. this.colors[colorIndex] = this.colors[colorIndex + 1] = this.colors[colorIndex + 2] = this.colors[colorIndex + 3] = displayObject.worldAlpha;
  32402. this.dirtyColors = true;
  32403. }
  32404. }
  32405. else
  32406. {
  32407. index = indexRun * 8;
  32408. this.verticies[index + 0 ] = 0;
  32409. this.verticies[index + 1 ] = 0;
  32410. this.verticies[index + 2 ] = 0;
  32411. this.verticies[index + 3 ] = 0;
  32412. this.verticies[index + 4 ] = 0;
  32413. this.verticies[index + 5 ] = 0;
  32414. this.verticies[index + 6] = 0;
  32415. this.verticies[index + 7] = 0;
  32416. }
  32417. indexRun++;
  32418. displayObject = displayObject.__next;
  32419. }
  32420. }
  32421. return Phaser;
  32422. });
  32423. // Copyright (c) 2012 Florian H., https://github.com/js-coder https://github.com/js-coder/cookie.js
  32424. !function (document, undefined) {
  32425. var cookie = function () {
  32426. return cookie.get.apply(cookie, arguments);
  32427. };
  32428. var utils = cookie.utils = {
  32429. // Is the given value an array? Use ES5 Array.isArray if it's available.
  32430. isArray: Array.isArray || function (value) {
  32431. return Object.prototype.toString.call(value) === '[object Array]';
  32432. },
  32433. // Is the given value a plain object / an object whose constructor is `Object`?
  32434. isPlainObject: function (value) {
  32435. return !!value && Object.prototype.toString.call(value) === '[object Object]';
  32436. },
  32437. // Convert an array-like object to an array – for example `arguments`.
  32438. toArray: function (value) {
  32439. return Array.prototype.slice.call(value);
  32440. },
  32441. // Get the keys of an object. Use ES5 Object.keys if it's available.
  32442. getKeys: Object.keys || function (obj) {
  32443. var keys = [],
  32444. key = '';
  32445. for (key in obj) {
  32446. if (obj.hasOwnProperty(key)) keys.push(key);
  32447. }
  32448. return keys;
  32449. },
  32450. // Unlike JavaScript's built-in escape functions, this method
  32451. // only escapes characters that are not allowed in cookies.
  32452. escape: function (value) {
  32453. return String(value).replace(/[,;"\\=\s%]/g, function (character) {
  32454. return encodeURIComponent(character);
  32455. });
  32456. },
  32457. // Return fallback if the value is not defined, otherwise return value.
  32458. retrieve: function (value, fallback) {
  32459. return value == null ? fallback : value;
  32460. }
  32461. };
  32462. cookie.defaults = {};
  32463. cookie.expiresMultiplier = 60 * 60 * 24;
  32464. cookie.set = function (key, value, options) {
  32465. if (utils.isPlainObject(key)) { // Then `key` contains an object with keys and values for cookies, `value` contains the options object.
  32466. for (var k in key) { // TODO: `k` really sucks as a variable name, but I didn't come up with a better one yet.
  32467. if (key.hasOwnProperty(k)) this.set(k, key[k], value);
  32468. }
  32469. } else {
  32470. options = utils.isPlainObject(options) ? options : { expires: options };
  32471. var expires = options.expires !== undefined ? options.expires : (this.defaults.expires || ''), // Empty string for session cookies.
  32472. expiresType = typeof(expires);
  32473. if (expiresType === 'string' && expires !== '') expires = new Date(expires);
  32474. else if (expiresType === 'number') expires = new Date(+new Date + 1000 * this.expiresMultiplier * expires); // This is needed because IE does not support the `max-age` cookie attribute.
  32475. if (expires !== '' && 'toGMTString' in expires) expires = ';expires=' + expires.toGMTString();
  32476. var path = options.path || this.defaults.path; // TODO: Too much code for a simple feature.
  32477. path = path ? ';path=' + path : '';
  32478. var domain = options.domain || this.defaults.domain;
  32479. domain = domain ? ';domain=' + domain : '';
  32480. var secure = options.secure || this.defaults.secure ? ';secure' : '';
  32481. document.cookie = utils.escape(key) + '=' + utils.escape(value) + expires + path + domain + secure;
  32482. }
  32483. return this; // Return the `cookie` object to make chaining possible.
  32484. };
  32485. // TODO: This is commented out, because I didn't come up with a better method name yet. Any ideas?
  32486. // cookie.setIfItDoesNotExist = function (key, value, options) {
  32487. // if (this.get(key) === undefined) this.set.call(this, arguments);
  32488. // },
  32489. cookie.remove = function (keys) {
  32490. keys = utils.isArray(keys) ? keys : utils.toArray(arguments);
  32491. for (var i = 0, l = keys.length; i < l; i++) {
  32492. this.set(keys[i], '', -1);
  32493. }
  32494. return this; // Return the `cookie` object to make chaining possible.
  32495. };
  32496. cookie.empty = function () {
  32497. return this.remove(utils.getKeys(this.all()));
  32498. };
  32499. cookie.get = function (keys, fallback) {
  32500. fallback = fallback || undefined;
  32501. var cookies = this.all();
  32502. if (utils.isArray(keys)) {
  32503. var result = {};
  32504. for (var i = 0, l = keys.length; i < l; i++) {
  32505. var value = keys[i];
  32506. result[value] = utils.retrieve(cookies[value], fallback);
  32507. }
  32508. return result;
  32509. } else return utils.retrieve(cookies[keys], fallback);
  32510. };
  32511. cookie.all = function () {
  32512. if (document.cookie === '') return {};
  32513. var cookies = document.cookie.split('; '),
  32514. result = {};
  32515. for (var i = 0, l = cookies.length; i < l; i++) {
  32516. var item = cookies[i].split('=');
  32517. result[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
  32518. }
  32519. return result;
  32520. };
  32521. cookie.enabled = function () {
  32522. if (navigator.cookieEnabled) return true;
  32523. var ret = cookie.set('_', '_').get('_') === '_';
  32524. cookie.remove('_');
  32525. return ret;
  32526. };
  32527. // If an AMD loader is present use AMD.
  32528. // If a CommonJS loader is present use CommonJS.
  32529. // Otherwise assign the `cookie` object to the global scope.
  32530. if (typeof define === 'function' && define.amd) {
  32531. define(function () {
  32532. return cookie;
  32533. });
  32534. } else if (typeof exports !== 'undefined') {
  32535. exports.cookie = cookie;
  32536. } else window.cookie = cookie;
  32537. }(document);
  32538. /*!
  32539. * VERSION: beta 1.9.3
  32540. * DATE: 2013-04-02
  32541. * UPDATES AND DOCS AT: http://www.greensock.com
  32542. *
  32543. * @license Copyright (c) 2008-2013, GreenSock. All rights reserved.
  32544. * This work is subject to the terms at http://www.greensock.com/terms_of_use.html or for
  32545. * Club GreenSock members, the software agreement that was issued with your membership.
  32546. *
  32547. * @author: Jack Doyle, jack@greensock.com
  32548. **/
  32549. (window._gsQueue || (window._gsQueue = [])).push( function() {
  32550. "use strict";
  32551. window._gsDefine("easing.Back", ["easing.Ease"], function(Ease) {
  32552. var w = (window.GreenSockGlobals || window),
  32553. gs = w.com.greensock,
  32554. _2PI = Math.PI * 2,
  32555. _HALF_PI = Math.PI / 2,
  32556. _class = gs._class,
  32557. _create = function(n, f) {
  32558. var C = _class("easing." + n, function(){}, true),
  32559. p = C.prototype = new Ease();
  32560. p.constructor = C;
  32561. p.getRatio = f;
  32562. return C;
  32563. },
  32564. _easeReg = Ease.register || function(){}, //put an empty function in place just as a safety measure in case someone loads an OLD version of TweenLite.js where Ease.register doesn't exist.
  32565. _wrap = function(name, EaseOut, EaseIn, EaseInOut, aliases) {
  32566. var C = _class("easing."+name, {
  32567. easeOut:new EaseOut(),
  32568. easeIn:new EaseIn(),
  32569. easeInOut:new EaseInOut()
  32570. }, true);
  32571. _easeReg(C, name);
  32572. return C;
  32573. },
  32574. EasePoint = function(time, value, next) {
  32575. this.t = time;
  32576. this.v = value;
  32577. if (next) {
  32578. this.next = next;
  32579. next.prev = this;
  32580. this.c = next.v - value;
  32581. this.gap = next.t - time;
  32582. }
  32583. },
  32584. //Back
  32585. _createBack = function(n, f) {
  32586. var C = _class("easing." + n, function(overshoot) {
  32587. this._p1 = (overshoot || overshoot === 0) ? overshoot : 1.70158;
  32588. this._p2 = this._p1 * 1.525;
  32589. }, true),
  32590. p = C.prototype = new Ease();
  32591. p.constructor = C;
  32592. p.getRatio = f;
  32593. p.config = function(overshoot) {
  32594. return new C(overshoot);
  32595. };
  32596. return C;
  32597. },
  32598. Back = _wrap("Back",
  32599. _createBack("BackOut", function(p) {
  32600. return ((p = p - 1) * p * ((this._p1 + 1) * p + this._p1) + 1);
  32601. }),
  32602. _createBack("BackIn", function(p) {
  32603. return p * p * ((this._p1 + 1) * p - this._p1);
  32604. }),
  32605. _createBack("BackInOut", function(p) {
  32606. return ((p *= 2) < 1) ? 0.5 * p * p * ((this._p2 + 1) * p - this._p2) : 0.5 * ((p -= 2) * p * ((this._p2 + 1) * p + this._p2) + 2);
  32607. })
  32608. ),
  32609. //SlowMo
  32610. SlowMo = _class("easing.SlowMo", function(linearRatio, power, yoyoMode) {
  32611. power = (power || power === 0) ? power : 0.7;
  32612. if (linearRatio == null) {
  32613. linearRatio = 0.7;
  32614. } else if (linearRatio > 1) {
  32615. linearRatio = 1;
  32616. }
  32617. this._p = (linearRatio !== 1) ? power : 0;
  32618. this._p1 = (1 - linearRatio) / 2;
  32619. this._p2 = linearRatio;
  32620. this._p3 = this._p1 + this._p2;
  32621. this._calcEnd = (yoyoMode === true);
  32622. }, true),
  32623. p = SlowMo.prototype = new Ease(),
  32624. SteppedEase, RoughEase, _createElastic;
  32625. p.constructor = SlowMo;
  32626. p.getRatio = function(p) {
  32627. var r = p + (0.5 - p) * this._p;
  32628. if (p < this._p1) {
  32629. return this._calcEnd ? 1 - ((p = 1 - (p / this._p1)) * p) : r - ((p = 1 - (p / this._p1)) * p * p * p * r);
  32630. } else if (p > this._p3) {
  32631. return this._calcEnd ? 1 - (p = (p - this._p3) / this._p1) * p : r + ((p - r) * (p = (p - this._p3) / this._p1) * p * p * p);
  32632. }
  32633. return this._calcEnd ? 1 : r;
  32634. };
  32635. SlowMo.ease = new SlowMo(0.7, 0.7);
  32636. p.config = SlowMo.config = function(linearRatio, power, yoyoMode) {
  32637. return new SlowMo(linearRatio, power, yoyoMode);
  32638. };
  32639. //SteppedEase
  32640. SteppedEase = _class("easing.SteppedEase", function(steps) {
  32641. steps = steps || 1;
  32642. this._p1 = 1 / steps;
  32643. this._p2 = steps + 1;
  32644. }, true);
  32645. p = SteppedEase.prototype = new Ease();
  32646. p.constructor = SteppedEase;
  32647. p.getRatio = function(p) {
  32648. if (p < 0) {
  32649. p = 0;
  32650. } else if (p >= 1) {
  32651. p = 0.999999999;
  32652. }
  32653. return ((this._p2 * p) >> 0) * this._p1;
  32654. };
  32655. p.config = SteppedEase.config = function(steps) {
  32656. return new SteppedEase(steps);
  32657. };
  32658. //RoughEase
  32659. RoughEase = _class("easing.RoughEase", function(vars) {
  32660. vars = vars || {};
  32661. var taper = vars.taper || "none",
  32662. a = [],
  32663. cnt = 0,
  32664. points = (vars.points || 20) | 0,
  32665. i = points,
  32666. randomize = (vars.randomize !== false),
  32667. clamp = (vars.clamp === true),
  32668. template = (vars.template instanceof Ease) ? vars.template : null,
  32669. strength = (typeof(vars.strength) === "number") ? vars.strength * 0.4 : 0.4,
  32670. x, y, bump, invX, obj, pnt;
  32671. while (--i > -1) {
  32672. x = randomize ? Math.random() : (1 / points) * i;
  32673. y = template ? template.getRatio(x) : x;
  32674. if (taper === "none") {
  32675. bump = strength;
  32676. } else if (taper === "out") {
  32677. invX = 1 - x;
  32678. bump = invX * invX * strength;
  32679. } else if (taper === "in") {
  32680. bump = x * x * strength;
  32681. } else if (x < 0.5) { //"both" (start)
  32682. invX = x * 2;
  32683. bump = invX * invX * 0.5 * strength;
  32684. } else { //"both" (end)
  32685. invX = (1 - x) * 2;
  32686. bump = invX * invX * 0.5 * strength;
  32687. }
  32688. if (randomize) {
  32689. y += (Math.random() * bump) - (bump * 0.5);
  32690. } else if (i % 2) {
  32691. y += bump * 0.5;
  32692. } else {
  32693. y -= bump * 0.5;
  32694. }
  32695. if (clamp) {
  32696. if (y > 1) {
  32697. y = 1;
  32698. } else if (y < 0) {
  32699. y = 0;
  32700. }
  32701. }
  32702. a[cnt++] = {x:x, y:y};
  32703. }
  32704. a.sort(function(a, b) {
  32705. return a.x - b.x;
  32706. });
  32707. pnt = new EasePoint(1, 1, null);
  32708. i = points;
  32709. while (--i > -1) {
  32710. obj = a[i];
  32711. pnt = new EasePoint(obj.x, obj.y, pnt);
  32712. }
  32713. this._prev = new EasePoint(0, 0, (pnt.t !== 0) ? pnt : pnt.next);
  32714. }, true);
  32715. p = RoughEase.prototype = new Ease();
  32716. p.constructor = RoughEase;
  32717. p.getRatio = function(p) {
  32718. var pnt = this._prev;
  32719. if (p > pnt.t) {
  32720. while (pnt.next && p >= pnt.t) {
  32721. pnt = pnt.next;
  32722. }
  32723. pnt = pnt.prev;
  32724. } else {
  32725. while (pnt.prev && p <= pnt.t) {
  32726. pnt = pnt.prev;
  32727. }
  32728. }
  32729. this._prev = pnt;
  32730. return (pnt.v + ((p - pnt.t) / pnt.gap) * pnt.c);
  32731. };
  32732. p.config = function(vars) {
  32733. return new RoughEase(vars);
  32734. };
  32735. RoughEase.ease = new RoughEase();
  32736. //Bounce
  32737. _wrap("Bounce",
  32738. _create("BounceOut", function(p) {
  32739. if (p < 1 / 2.75) {
  32740. return 7.5625 * p * p;
  32741. } else if (p < 2 / 2.75) {
  32742. return 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
  32743. } else if (p < 2.5 / 2.75) {
  32744. return 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
  32745. }
  32746. return 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
  32747. }),
  32748. _create("BounceIn", function(p) {
  32749. if ((p = 1 - p) < 1 / 2.75) {
  32750. return 1 - (7.5625 * p * p);
  32751. } else if (p < 2 / 2.75) {
  32752. return 1 - (7.5625 * (p -= 1.5 / 2.75) * p + 0.75);
  32753. } else if (p < 2.5 / 2.75) {
  32754. return 1 - (7.5625 * (p -= 2.25 / 2.75) * p + 0.9375);
  32755. }
  32756. return 1 - (7.5625 * (p -= 2.625 / 2.75) * p + 0.984375);
  32757. }),
  32758. _create("BounceInOut", function(p) {
  32759. var invert = (p < 0.5);
  32760. if (invert) {
  32761. p = 1 - (p * 2);
  32762. } else {
  32763. p = (p * 2) - 1;
  32764. }
  32765. if (p < 1 / 2.75) {
  32766. p = 7.5625 * p * p;
  32767. } else if (p < 2 / 2.75) {
  32768. p = 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
  32769. } else if (p < 2.5 / 2.75) {
  32770. p = 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
  32771. } else {
  32772. p = 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
  32773. }
  32774. return invert ? (1 - p) * 0.5 : p * 0.5 + 0.5;
  32775. })
  32776. );
  32777. //CIRC
  32778. _wrap("Circ",
  32779. _create("CircOut", function(p) {
  32780. return Math.sqrt(1 - (p = p - 1) * p);
  32781. }),
  32782. _create("CircIn", function(p) {
  32783. return -(Math.sqrt(1 - (p * p)) - 1);
  32784. }),
  32785. _create("CircInOut", function(p) {
  32786. return ((p*=2) < 1) ? -0.5 * (Math.sqrt(1 - p * p) - 1) : 0.5 * (Math.sqrt(1 - (p -= 2) * p) + 1);
  32787. })
  32788. );
  32789. //Elastic
  32790. _createElastic = function(n, f, def) {
  32791. var C = _class("easing." + n, function(amplitude, period) {
  32792. this._p1 = amplitude || 1;
  32793. this._p2 = period || def;
  32794. this._p3 = this._p2 / _2PI * (Math.asin(1 / this._p1) || 0);
  32795. }, true),
  32796. p = C.prototype = new Ease();
  32797. p.constructor = C;
  32798. p.getRatio = f;
  32799. p.config = function(amplitude, period) {
  32800. return new C(amplitude, period);
  32801. };
  32802. return C;
  32803. };
  32804. _wrap("Elastic",
  32805. _createElastic("ElasticOut", function(p) {
  32806. return this._p1 * Math.pow(2, -10 * p) * Math.sin( (p - this._p3) * _2PI / this._p2 ) + 1;
  32807. }, 0.3),
  32808. _createElastic("ElasticIn", function(p) {
  32809. return -(this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * _2PI / this._p2 ));
  32810. }, 0.3),
  32811. _createElastic("ElasticInOut", function(p) {
  32812. return ((p *= 2) < 1) ? -0.5 * (this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * _2PI / this._p2)) : this._p1 * Math.pow(2, -10 *(p -= 1)) * Math.sin( (p - this._p3) * _2PI / this._p2 ) *0.5 + 1;
  32813. }, 0.45)
  32814. );
  32815. //Expo
  32816. _wrap("Expo",
  32817. _create("ExpoOut", function(p) {
  32818. return 1 - Math.pow(2, -10 * p);
  32819. }),
  32820. _create("ExpoIn", function(p) {
  32821. return Math.pow(2, 10 * (p - 1)) - 0.001;
  32822. }),
  32823. _create("ExpoInOut", function(p) {
  32824. return ((p *= 2) < 1) ? 0.5 * Math.pow(2, 10 * (p - 1)) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));
  32825. })
  32826. );
  32827. //Sine
  32828. _wrap("Sine",
  32829. _create("SineOut", function(p) {
  32830. return Math.sin(p * _HALF_PI);
  32831. }),
  32832. _create("SineIn", function(p) {
  32833. return -Math.cos(p * _HALF_PI) + 1;
  32834. }),
  32835. _create("SineInOut", function(p) {
  32836. return -0.5 * (Math.cos(Math.PI * p) - 1);
  32837. })
  32838. );
  32839. _class("easing.EaseLookup", {
  32840. find:function(s) {
  32841. return Ease.map[s];
  32842. }
  32843. }, true);
  32844. //register the non-standard eases
  32845. _easeReg(w.SlowMo, "SlowMo", "ease,");
  32846. _easeReg(RoughEase, "RoughEase", "ease,");
  32847. _easeReg(SteppedEase, "SteppedEase", "ease,");
  32848. return Back;
  32849. }, true);
  32850. }); if (window._gsDefine) { window._gsQueue.pop()(); }
  32851. /*!
  32852. * VERSION: 1.11.0
  32853. * DATE: 2013-10-21
  32854. * UPDATES AND DOCS AT: http://www.greensock.com
  32855. *
  32856. * @license Copyright (c) 2008-2013, GreenSock. All rights reserved.
  32857. * This work is subject to the terms at http://www.greensock.com/terms_of_use.html or for
  32858. * Club GreenSock members, the software agreement that was issued with your membership.
  32859. *
  32860. * @author: Jack Doyle, jack@greensock.com
  32861. */
  32862. (window._gsQueue || (window._gsQueue = [])).push( function() {
  32863. "use strict";
  32864. window._gsDefine("TimelineLite", ["core.Animation","core.SimpleTimeline","TweenLite"], function(Animation, SimpleTimeline, TweenLite) {
  32865. var TimelineLite = function(vars) {
  32866. SimpleTimeline.call(this, vars);
  32867. this._labels = {};
  32868. this.autoRemoveChildren = (this.vars.autoRemoveChildren === true);
  32869. this.smoothChildTiming = (this.vars.smoothChildTiming === true);
  32870. this._sortChildren = true;
  32871. this._onUpdate = this.vars.onUpdate;
  32872. var v = this.vars,
  32873. val, p;
  32874. for (p in v) {
  32875. val = v[p];
  32876. if (_isArray(val)) if (val.join("").indexOf("{self}") !== -1) {
  32877. v[p] = this._swapSelfInParams(val);
  32878. }
  32879. }
  32880. if (_isArray(v.tweens)) {
  32881. this.add(v.tweens, 0, v.align, v.stagger);
  32882. }
  32883. },
  32884. _tinyNum = 0.0000000001,
  32885. _isSelector = TweenLite._internals.isSelector,
  32886. _isArray = TweenLite._internals.isArray,
  32887. _blankArray = [],
  32888. _copy = function(vars) {
  32889. var copy = {}, p;
  32890. for (p in vars) {
  32891. copy[p] = vars[p];
  32892. }
  32893. return copy;
  32894. },
  32895. _pauseCallback = function(tween, callback, params, scope) {
  32896. tween._timeline.pause(tween._startTime);
  32897. if (callback) {
  32898. callback.apply(scope || tween._timeline, params || _blankArray);
  32899. }
  32900. },
  32901. _slice = _blankArray.slice,
  32902. p = TimelineLite.prototype = new SimpleTimeline();
  32903. TimelineLite.version = "1.11.0";
  32904. p.constructor = TimelineLite;
  32905. p.kill()._gc = false;
  32906. p.to = function(target, duration, vars, position) {
  32907. return duration ? this.add( new TweenLite(target, duration, vars), position) : this.set(target, vars, position);
  32908. };
  32909. p.from = function(target, duration, vars, position) {
  32910. return this.add( TweenLite.from(target, duration, vars), position);
  32911. };
  32912. p.fromTo = function(target, duration, fromVars, toVars, position) {
  32913. return duration ? this.add( TweenLite.fromTo(target, duration, fromVars, toVars), position) : this.set(target, toVars, position);
  32914. };
  32915. p.staggerTo = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
  32916. var tl = new TimelineLite({onComplete:onCompleteAll, onCompleteParams:onCompleteAllParams, onCompleteScope:onCompleteAllScope}),
  32917. i;
  32918. if (typeof(targets) === "string") {
  32919. targets = TweenLite.selector(targets) || targets;
  32920. }
  32921. if (_isSelector(targets)) { //senses if the targets object is a selector. If it is, we should translate it into an array.
  32922. targets = _slice.call(targets, 0);
  32923. }
  32924. stagger = stagger || 0;
  32925. for (i = 0; i < targets.length; i++) {
  32926. if (vars.startAt) {
  32927. vars.startAt = _copy(vars.startAt);
  32928. }
  32929. tl.to(targets[i], duration, _copy(vars), i * stagger);
  32930. }
  32931. return this.add(tl, position);
  32932. };
  32933. p.staggerFrom = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
  32934. vars.immediateRender = (vars.immediateRender != false);
  32935. vars.runBackwards = true;
  32936. return this.staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
  32937. };
  32938. p.staggerFromTo = function(targets, duration, fromVars, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
  32939. toVars.startAt = fromVars;
  32940. toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
  32941. return this.staggerTo(targets, duration, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
  32942. };
  32943. p.call = function(callback, params, scope, position) {
  32944. return this.add( TweenLite.delayedCall(0, callback, params, scope), position);
  32945. };
  32946. p.set = function(target, vars, position) {
  32947. position = this._parseTimeOrLabel(position, 0, true);
  32948. if (vars.immediateRender == null) {
  32949. vars.immediateRender = (position === this._time && !this._paused);
  32950. }
  32951. return this.add( new TweenLite(target, 0, vars), position);
  32952. };
  32953. TimelineLite.exportRoot = function(vars, ignoreDelayedCalls) {
  32954. vars = vars || {};
  32955. if (vars.smoothChildTiming == null) {
  32956. vars.smoothChildTiming = true;
  32957. }
  32958. var tl = new TimelineLite(vars),
  32959. root = tl._timeline,
  32960. tween, next;
  32961. if (ignoreDelayedCalls == null) {
  32962. ignoreDelayedCalls = true;
  32963. }
  32964. root._remove(tl, true);
  32965. tl._startTime = 0;
  32966. tl._rawPrevTime = tl._time = tl._totalTime = root._time;
  32967. tween = root._first;
  32968. while (tween) {
  32969. next = tween._next;
  32970. if (!ignoreDelayedCalls || !(tween instanceof TweenLite && tween.target === tween.vars.onComplete)) {
  32971. tl.add(tween, tween._startTime - tween._delay);
  32972. }
  32973. tween = next;
  32974. }
  32975. root.add(tl, 0);
  32976. return tl;
  32977. };
  32978. p.add = function(value, position, align, stagger) {
  32979. var curTime, l, i, child, tl, beforeRawTime;
  32980. if (typeof(position) !== "number") {
  32981. position = this._parseTimeOrLabel(position, 0, true, value);
  32982. }
  32983. if (!(value instanceof Animation)) {
  32984. if ((value instanceof Array) || (value && value.push && _isArray(value))) {
  32985. align = align || "normal";
  32986. stagger = stagger || 0;
  32987. curTime = position;
  32988. l = value.length;
  32989. for (i = 0; i < l; i++) {
  32990. if (_isArray(child = value[i])) {
  32991. child = new TimelineLite({tweens:child});
  32992. }
  32993. this.add(child, curTime);
  32994. if (typeof(child) !== "string" && typeof(child) !== "function") {
  32995. if (align === "sequence") {
  32996. curTime = child._startTime + (child.totalDuration() / child._timeScale);
  32997. } else if (align === "start") {
  32998. child._startTime -= child.delay();
  32999. }
  33000. }
  33001. curTime += stagger;
  33002. }
  33003. return this._uncache(true);
  33004. } else if (typeof(value) === "string") {
  33005. return this.addLabel(value, position);
  33006. } else if (typeof(value) === "function") {
  33007. value = TweenLite.delayedCall(0, value);
  33008. } else {
  33009. throw("Cannot add " + value + " into the timeline; it is not a tween, timeline, function, or string.");
  33010. }
  33011. }
  33012. SimpleTimeline.prototype.add.call(this, value, position);
  33013. //if the timeline has already ended but the inserted tween/timeline extends the duration, we should enable this timeline again so that it renders properly.
  33014. if (this._gc) if (!this._paused) if (this._duration < this.duration()) {
  33015. //in case any of the anscestors had completed but should now be enabled...
  33016. tl = this;
  33017. beforeRawTime = (tl.rawTime() > value._startTime); //if the tween is placed on the timeline so that it starts BEFORE the current rawTime, we should align the playhead (move the timeline). This is because sometimes users will create a timeline, let it finish, and much later append a tween and expect it to run instead of jumping to its end state. While technically one could argue that it should jump to its end state, that's not what users intuitively expect.
  33018. while (tl._gc && tl._timeline) {
  33019. if (tl._timeline.smoothChildTiming && beforeRawTime) {
  33020. tl.totalTime(tl._totalTime, true); //moves the timeline (shifts its startTime) if necessary, and also enables it.
  33021. } else {
  33022. tl._enabled(true, false);
  33023. }
  33024. tl = tl._timeline;
  33025. }
  33026. }
  33027. return this;
  33028. };
  33029. p.remove = function(value) {
  33030. if (value instanceof Animation) {
  33031. return this._remove(value, false);
  33032. } else if (value instanceof Array || (value && value.push && _isArray(value))) {
  33033. var i = value.length;
  33034. while (--i > -1) {
  33035. this.remove(value[i]);
  33036. }
  33037. return this;
  33038. } else if (typeof(value) === "string") {
  33039. return this.removeLabel(value);
  33040. }
  33041. return this.kill(null, value);
  33042. };
  33043. p._remove = function(tween, skipDisable) {
  33044. SimpleTimeline.prototype._remove.call(this, tween, skipDisable);
  33045. var last = this._last;
  33046. if (!last) {
  33047. this._time = this._totalTime = 0;
  33048. } else if (this._time > last._startTime + last._totalDuration / last._timeScale) {
  33049. this._time = this.duration();
  33050. this._totalTime = this._totalDuration;
  33051. }
  33052. return this;
  33053. };
  33054. p.append = function(value, offsetOrLabel) {
  33055. return this.add(value, this._parseTimeOrLabel(null, offsetOrLabel, true, value));
  33056. };
  33057. p.insert = p.insertMultiple = function(value, position, align, stagger) {
  33058. return this.add(value, position || 0, align, stagger);
  33059. };
  33060. p.appendMultiple = function(tweens, offsetOrLabel, align, stagger) {
  33061. return this.add(tweens, this._parseTimeOrLabel(null, offsetOrLabel, true, tweens), align, stagger);
  33062. };
  33063. p.addLabel = function(label, position) {
  33064. this._labels[label] = this._parseTimeOrLabel(position);
  33065. return this;
  33066. };
  33067. p.addPause = function(position, callback, params, scope) {
  33068. return this.call(_pauseCallback, ["{self}", callback, params, scope], this, position);
  33069. };
  33070. p.removeLabel = function(label) {
  33071. delete this._labels[label];
  33072. return this;
  33073. };
  33074. p.getLabelTime = function(label) {
  33075. return (this._labels[label] != null) ? this._labels[label] : -1;
  33076. };
  33077. p._parseTimeOrLabel = function(timeOrLabel, offsetOrLabel, appendIfAbsent, ignore) {
  33078. var i;
  33079. //if we're about to add a tween/timeline (or an array of them) that's already a child of this timeline, we should remove it first so that it doesn't contaminate the duration().
  33080. if (ignore instanceof Animation && ignore.timeline === this) {
  33081. this.remove(ignore);
  33082. } else if (ignore && ((ignore instanceof Array) || (ignore.push && _isArray(ignore)))) {
  33083. i = ignore.length;
  33084. while (--i > -1) {
  33085. if (ignore[i] instanceof Animation && ignore[i].timeline === this) {
  33086. this.remove(ignore[i]);
  33087. }
  33088. }
  33089. }
  33090. if (typeof(offsetOrLabel) === "string") {
  33091. return this._parseTimeOrLabel(offsetOrLabel, (appendIfAbsent && typeof(timeOrLabel) === "number" && this._labels[offsetOrLabel] == null) ? timeOrLabel - this.duration() : 0, appendIfAbsent);
  33092. }
  33093. offsetOrLabel = offsetOrLabel || 0;
  33094. if (typeof(timeOrLabel) === "string" && (isNaN(timeOrLabel) || this._labels[timeOrLabel] != null)) { //if the string is a number like "1", check to see if there's a label with that name, otherwise interpret it as a number (absolute value).
  33095. i = timeOrLabel.indexOf("=");
  33096. if (i === -1) {
  33097. if (this._labels[timeOrLabel] == null) {
  33098. return appendIfAbsent ? (this._labels[timeOrLabel] = this.duration() + offsetOrLabel) : offsetOrLabel;
  33099. }
  33100. return this._labels[timeOrLabel] + offsetOrLabel;
  33101. }
  33102. offsetOrLabel = parseInt(timeOrLabel.charAt(i-1) + "1", 10) * Number(timeOrLabel.substr(i+1));
  33103. timeOrLabel = (i > 1) ? this._parseTimeOrLabel(timeOrLabel.substr(0, i-1), 0, appendIfAbsent) : this.duration();
  33104. } else if (timeOrLabel == null) {
  33105. timeOrLabel = this.duration();
  33106. }
  33107. return Number(timeOrLabel) + offsetOrLabel;
  33108. };
  33109. p.seek = function(position, suppressEvents) {
  33110. return this.totalTime((typeof(position) === "number") ? position : this._parseTimeOrLabel(position), (suppressEvents !== false));
  33111. };
  33112. p.stop = function() {
  33113. return this.paused(true);
  33114. };
  33115. p.gotoAndPlay = function(position, suppressEvents) {
  33116. return this.play(position, suppressEvents);
  33117. };
  33118. p.gotoAndStop = function(position, suppressEvents) {
  33119. return this.pause(position, suppressEvents);
  33120. };
  33121. p.render = function(time, suppressEvents, force) {
  33122. if (this._gc) {
  33123. this._enabled(true, false);
  33124. }
  33125. var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(),
  33126. prevTime = this._time,
  33127. prevStart = this._startTime,
  33128. prevTimeScale = this._timeScale,
  33129. prevPaused = this._paused,
  33130. tween, isComplete, next, callback, internalForce;
  33131. if (time >= totalDur) {
  33132. this._totalTime = this._time = totalDur;
  33133. if (!this._reversed) if (!this._hasPausedChild()) {
  33134. isComplete = true;
  33135. callback = "onComplete";
  33136. if (this._duration === 0) if (time === 0 || this._rawPrevTime < 0 || this._rawPrevTime === _tinyNum) if (this._rawPrevTime !== time && this._first) {
  33137. internalForce = true;
  33138. if (this._rawPrevTime > _tinyNum) {
  33139. callback = "onReverseComplete";
  33140. }
  33141. }
  33142. }
  33143. this._rawPrevTime = (this._duration || !suppressEvents || time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  33144. time = totalDur + 0.000001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off)
  33145. } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
  33146. this._totalTime = this._time = 0;
  33147. if (prevTime !== 0 || (this._duration === 0 && (this._rawPrevTime > _tinyNum || (time < 0 && this._rawPrevTime >= 0)))) {
  33148. callback = "onReverseComplete";
  33149. isComplete = this._reversed;
  33150. }
  33151. if (time < 0) {
  33152. this._active = false;
  33153. if (this._duration === 0) if (this._rawPrevTime >= 0 && this._first) { //zero-duration timelines are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
  33154. internalForce = true;
  33155. }
  33156. this._rawPrevTime = time;
  33157. } else {
  33158. this._rawPrevTime = (this._duration || !suppressEvents || time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  33159. time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline)
  33160. if (!this._initted) {
  33161. internalForce = true;
  33162. }
  33163. }
  33164. } else {
  33165. this._totalTime = this._time = this._rawPrevTime = time;
  33166. }
  33167. if ((this._time === prevTime || !this._first) && !force && !internalForce) {
  33168. return;
  33169. } else if (!this._initted) {
  33170. this._initted = true;
  33171. }
  33172. if (!this._active) if (!this._paused && this._time !== prevTime && time > 0) {
  33173. this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example.
  33174. }
  33175. if (prevTime === 0) if (this.vars.onStart) if (this._time !== 0) if (!suppressEvents) {
  33176. this.vars.onStart.apply(this.vars.onStartScope || this, this.vars.onStartParams || _blankArray);
  33177. }
  33178. if (this._time >= prevTime) {
  33179. tween = this._first;
  33180. while (tween) {
  33181. next = tween._next; //record it here because the value could change after rendering...
  33182. if (this._paused && !prevPaused) { //in case a tween pauses the timeline when rendering
  33183. break;
  33184. } else if (tween._active || (tween._startTime <= this._time && !tween._paused && !tween._gc)) {
  33185. if (!tween._reversed) {
  33186. tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
  33187. } else {
  33188. tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
  33189. }
  33190. }
  33191. tween = next;
  33192. }
  33193. } else {
  33194. tween = this._last;
  33195. while (tween) {
  33196. next = tween._prev; //record it here because the value could change after rendering...
  33197. if (this._paused && !prevPaused) { //in case a tween pauses the timeline when rendering
  33198. break;
  33199. } else if (tween._active || (tween._startTime <= prevTime && !tween._paused && !tween._gc)) {
  33200. if (!tween._reversed) {
  33201. tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
  33202. } else {
  33203. tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
  33204. }
  33205. }
  33206. tween = next;
  33207. }
  33208. }
  33209. if (this._onUpdate) if (!suppressEvents) {
  33210. this._onUpdate.apply(this.vars.onUpdateScope || this, this.vars.onUpdateParams || _blankArray);
  33211. }
  33212. if (callback) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate
  33213. if (isComplete) {
  33214. if (this._timeline.autoRemoveChildren) {
  33215. this._enabled(false, false);
  33216. }
  33217. this._active = false;
  33218. }
  33219. if (!suppressEvents && this.vars[callback]) {
  33220. this.vars[callback].apply(this.vars[callback + "Scope"] || this, this.vars[callback + "Params"] || _blankArray);
  33221. }
  33222. }
  33223. };
  33224. p._hasPausedChild = function() {
  33225. var tween = this._first;
  33226. while (tween) {
  33227. if (tween._paused || ((tween instanceof TimelineLite) && tween._hasPausedChild())) {
  33228. return true;
  33229. }
  33230. tween = tween._next;
  33231. }
  33232. return false;
  33233. };
  33234. p.getChildren = function(nested, tweens, timelines, ignoreBeforeTime) {
  33235. ignoreBeforeTime = ignoreBeforeTime || -9999999999;
  33236. var a = [],
  33237. tween = this._first,
  33238. cnt = 0;
  33239. while (tween) {
  33240. if (tween._startTime < ignoreBeforeTime) {
  33241. //do nothing
  33242. } else if (tween instanceof TweenLite) {
  33243. if (tweens !== false) {
  33244. a[cnt++] = tween;
  33245. }
  33246. } else {
  33247. if (timelines !== false) {
  33248. a[cnt++] = tween;
  33249. }
  33250. if (nested !== false) {
  33251. a = a.concat(tween.getChildren(true, tweens, timelines));
  33252. cnt = a.length;
  33253. }
  33254. }
  33255. tween = tween._next;
  33256. }
  33257. return a;
  33258. };
  33259. p.getTweensOf = function(target, nested) {
  33260. var tweens = TweenLite.getTweensOf(target),
  33261. i = tweens.length,
  33262. a = [],
  33263. cnt = 0;
  33264. while (--i > -1) {
  33265. if (tweens[i].timeline === this || (nested && this._contains(tweens[i]))) {
  33266. a[cnt++] = tweens[i];
  33267. }
  33268. }
  33269. return a;
  33270. };
  33271. p._contains = function(tween) {
  33272. var tl = tween.timeline;
  33273. while (tl) {
  33274. if (tl === this) {
  33275. return true;
  33276. }
  33277. tl = tl.timeline;
  33278. }
  33279. return false;
  33280. };
  33281. p.shiftChildren = function(amount, adjustLabels, ignoreBeforeTime) {
  33282. ignoreBeforeTime = ignoreBeforeTime || 0;
  33283. var tween = this._first,
  33284. labels = this._labels,
  33285. p;
  33286. while (tween) {
  33287. if (tween._startTime >= ignoreBeforeTime) {
  33288. tween._startTime += amount;
  33289. }
  33290. tween = tween._next;
  33291. }
  33292. if (adjustLabels) {
  33293. for (p in labels) {
  33294. if (labels[p] >= ignoreBeforeTime) {
  33295. labels[p] += amount;
  33296. }
  33297. }
  33298. }
  33299. return this._uncache(true);
  33300. };
  33301. p._kill = function(vars, target) {
  33302. if (!vars && !target) {
  33303. return this._enabled(false, false);
  33304. }
  33305. var tweens = (!target) ? this.getChildren(true, true, false) : this.getTweensOf(target),
  33306. i = tweens.length,
  33307. changed = false;
  33308. while (--i > -1) {
  33309. if (tweens[i]._kill(vars, target)) {
  33310. changed = true;
  33311. }
  33312. }
  33313. return changed;
  33314. };
  33315. p.clear = function(labels) {
  33316. var tweens = this.getChildren(false, true, true),
  33317. i = tweens.length;
  33318. this._time = this._totalTime = 0;
  33319. while (--i > -1) {
  33320. tweens[i]._enabled(false, false);
  33321. }
  33322. if (labels !== false) {
  33323. this._labels = {};
  33324. }
  33325. return this._uncache(true);
  33326. };
  33327. p.invalidate = function() {
  33328. var tween = this._first;
  33329. while (tween) {
  33330. tween.invalidate();
  33331. tween = tween._next;
  33332. }
  33333. return this;
  33334. };
  33335. p._enabled = function(enabled, ignoreTimeline) {
  33336. if (enabled === this._gc) {
  33337. var tween = this._first;
  33338. while (tween) {
  33339. tween._enabled(enabled, true);
  33340. tween = tween._next;
  33341. }
  33342. }
  33343. return SimpleTimeline.prototype._enabled.call(this, enabled, ignoreTimeline);
  33344. };
  33345. p.duration = function(value) {
  33346. if (!arguments.length) {
  33347. if (this._dirty) {
  33348. this.totalDuration(); //just triggers recalculation
  33349. }
  33350. return this._duration;
  33351. }
  33352. if (this.duration() !== 0 && value !== 0) {
  33353. this.timeScale(this._duration / value);
  33354. }
  33355. return this;
  33356. };
  33357. p.totalDuration = function(value) {
  33358. if (!arguments.length) {
  33359. if (this._dirty) {
  33360. var max = 0,
  33361. tween = this._last,
  33362. prevStart = 999999999999,
  33363. prev, end;
  33364. while (tween) {
  33365. prev = tween._prev; //record it here in case the tween changes position in the sequence...
  33366. if (tween._dirty) {
  33367. tween.totalDuration(); //could change the tween._startTime, so make sure the tween's cache is clean before analyzing it.
  33368. }
  33369. if (tween._startTime > prevStart && this._sortChildren && !tween._paused) { //in case one of the tweens shifted out of order, it needs to be re-inserted into the correct position in the sequence
  33370. this.add(tween, tween._startTime - tween._delay);
  33371. } else {
  33372. prevStart = tween._startTime;
  33373. }
  33374. if (tween._startTime < 0 && !tween._paused) { //children aren't allowed to have negative startTimes unless smoothChildTiming is true, so adjust here if one is found.
  33375. max -= tween._startTime;
  33376. if (this._timeline.smoothChildTiming) {
  33377. this._startTime += tween._startTime / this._timeScale;
  33378. }
  33379. this.shiftChildren(-tween._startTime, false, -9999999999);
  33380. prevStart = 0;
  33381. }
  33382. end = tween._startTime + (tween._totalDuration / tween._timeScale);
  33383. if (end > max) {
  33384. max = end;
  33385. }
  33386. tween = prev;
  33387. }
  33388. this._duration = this._totalDuration = max;
  33389. this._dirty = false;
  33390. }
  33391. return this._totalDuration;
  33392. }
  33393. if (this.totalDuration() !== 0) if (value !== 0) {
  33394. this.timeScale(this._totalDuration / value);
  33395. }
  33396. return this;
  33397. };
  33398. p.usesFrames = function() {
  33399. var tl = this._timeline;
  33400. while (tl._timeline) {
  33401. tl = tl._timeline;
  33402. }
  33403. return (tl === Animation._rootFramesTimeline);
  33404. };
  33405. p.rawTime = function() {
  33406. return this._paused ? this._totalTime : (this._timeline.rawTime() - this._startTime) * this._timeScale;
  33407. };
  33408. return TimelineLite;
  33409. }, true);
  33410. }); if (window._gsDefine) { window._gsQueue.pop()(); }
  33411. /*!
  33412. * VERSION: 1.11.2
  33413. * DATE: 2013-11-20
  33414. * UPDATES AND DOCS AT: http://www.greensock.com
  33415. *
  33416. * @license Copyright (c) 2008-2013, GreenSock. All rights reserved.
  33417. * This work is subject to the terms at http://www.greensock.com/terms_of_use.html or for
  33418. * Club GreenSock members, the software agreement that was issued with your membership.
  33419. *
  33420. * @author: Jack Doyle, jack@greensock.com
  33421. */
  33422. (function(window) {
  33423. "use strict";
  33424. var _globals = window.GreenSockGlobals || window;
  33425. if (_globals.TweenLite) {
  33426. return; //in case the core set of classes is already loaded, don't instantiate twice.
  33427. }
  33428. var _namespace = function(ns) {
  33429. var a = ns.split("."),
  33430. p = _globals, i;
  33431. for (i = 0; i < a.length; i++) {
  33432. p[a[i]] = p = p[a[i]] || {};
  33433. }
  33434. return p;
  33435. },
  33436. gs = _namespace("com.greensock"),
  33437. _tinyNum = 0.0000000001,
  33438. _slice = [].slice,
  33439. _emptyFunc = function() {},
  33440. _isArray = (function() { //works around issues in iframe environments where the Array global isn't shared, thus if the object originates in a different window/iframe, "(obj instanceof Array)" will evaluate false. We added some speed optimizations to avoid Object.prototype.toString.call() unless it's absolutely necessary because it's VERY slow (like 20x slower)
  33441. var toString = Object.prototype.toString,
  33442. array = toString.call([]);
  33443. return function(obj) {
  33444. return (obj instanceof Array || (typeof(obj) === "object" && !!obj.push && toString.call(obj) === array));
  33445. };
  33446. }()),
  33447. a, i, p, _ticker, _tickerActive,
  33448. _defLookup = {},
  33449. /**
  33450. * @constructor
  33451. * Defines a GreenSock class, optionally with an array of dependencies that must be instantiated first and passed into the definition.
  33452. * This allows users to load GreenSock JS files in any order even if they have interdependencies (like CSSPlugin extends TweenPlugin which is
  33453. * inside TweenLite.js, but if CSSPlugin is loaded first, it should wait to run its code until TweenLite.js loads and instantiates TweenPlugin
  33454. * and then pass TweenPlugin to CSSPlugin's definition). This is all done automatically and internally.
  33455. *
  33456. * Every definition will be added to a "com.greensock" global object (typically window, but if a window.GreenSockGlobals object is found,
  33457. * it will go there as of v1.7). For example, TweenLite will be found at window.com.greensock.TweenLite and since it's a global class that should be available anywhere,
  33458. * it is ALSO referenced at window.TweenLite. However some classes aren't considered global, like the base com.greensock.core.Animation class, so
  33459. * those will only be at the package like window.com.greensock.core.Animation. Again, if you define a GreenSockGlobals object on the window, everything
  33460. * gets tucked neatly inside there instead of on the window directly. This allows you to do advanced things like load multiple versions of GreenSock
  33461. * files and put them into distinct objects (imagine a banner ad uses a newer version but the main site uses an older one). In that case, you could
  33462. * sandbox the banner one like:
  33463. *
  33464. * <script>
  33465. * var gs = window.GreenSockGlobals = {}; //the newer version we're about to load could now be referenced in a "gs" object, like gs.TweenLite.to(...). Use whatever alias you want as long as it's unique, "gs" or "banner" or whatever.
  33466. * </script>
  33467. * <script src="js/greensock/v1.7/TweenMax.js"></script>
  33468. * <script>
  33469. * window.GreenSockGlobals = null; //reset it back to null so that the next load of TweenMax affects the window and we can reference things directly like TweenLite.to(...)
  33470. * </script>
  33471. * <script src="js/greensock/v1.6/TweenMax.js"></script>
  33472. * <script>
  33473. * gs.TweenLite.to(...); //would use v1.7
  33474. * TweenLite.to(...); //would use v1.6
  33475. * </script>
  33476. *
  33477. * @param {!string} ns The namespace of the class definition, leaving off "com.greensock." as that's assumed. For example, "TweenLite" or "plugins.CSSPlugin" or "easing.Back".
  33478. * @param {!Array.<string>} dependencies An array of dependencies (described as their namespaces minus "com.greensock." prefix). For example ["TweenLite","plugins.TweenPlugin","core.Animation"]
  33479. * @param {!function():Object} func The function that should be called and passed the resolved dependencies which will return the actual class for this definition.
  33480. * @param {boolean=} global If true, the class will be added to the global scope (typically window unless you define a window.GreenSockGlobals object)
  33481. */
  33482. Definition = function(ns, dependencies, func, global) {
  33483. this.sc = (_defLookup[ns]) ? _defLookup[ns].sc : []; //subclasses
  33484. _defLookup[ns] = this;
  33485. this.gsClass = null;
  33486. this.func = func;
  33487. var _classes = [];
  33488. this.check = function(init) {
  33489. var i = dependencies.length,
  33490. missing = i,
  33491. cur, a, n, cl;
  33492. while (--i > -1) {
  33493. if ((cur = _defLookup[dependencies[i]] || new Definition(dependencies[i], [])).gsClass) {
  33494. _classes[i] = cur.gsClass;
  33495. missing--;
  33496. } else if (init) {
  33497. cur.sc.push(this);
  33498. }
  33499. }
  33500. if (missing === 0 && func) {
  33501. a = ("com.greensock." + ns).split(".");
  33502. n = a.pop();
  33503. cl = _namespace(a.join("."))[n] = this.gsClass = func.apply(func, _classes);
  33504. //exports to multiple environments
  33505. if (global) {
  33506. _globals[n] = cl; //provides a way to avoid global namespace pollution. By default, the main classes like TweenLite, Power1, Strong, etc. are added to window unless a GreenSockGlobals is defined. So if you want to have things added to a custom object instead, just do something like window.GreenSockGlobals = {} before loading any GreenSock files. You can even set up an alias like window.GreenSockGlobals = windows.gs = {} so that you can access everything like gs.TweenLite. Also remember that ALL classes are added to the window.com.greensock object (in their respective packages, like com.greensock.easing.Power1, com.greensock.TweenLite, etc.)
  33507. if (typeof(define) === "function" && define.amd){ //AMD
  33508. define((window.GreenSockAMDPath ? window.GreenSockAMDPath + "/" : "") + ns.split(".").join("/"), [], function() { return cl; });
  33509. } else if (typeof(module) !== "undefined" && module.exports){ //node
  33510. module.exports = cl;
  33511. }
  33512. }
  33513. for (i = 0; i < this.sc.length; i++) {
  33514. this.sc[i].check();
  33515. }
  33516. }
  33517. };
  33518. this.check(true);
  33519. },
  33520. //used to create Definition instances (which basically registers a class that has dependencies).
  33521. _gsDefine = window._gsDefine = function(ns, dependencies, func, global) {
  33522. return new Definition(ns, dependencies, func, global);
  33523. },
  33524. //a quick way to create a class that doesn't have any dependencies. Returns the class, but first registers it in the GreenSock namespace so that other classes can grab it (other classes might be dependent on the class).
  33525. _class = gs._class = function(ns, func, global) {
  33526. func = func || function() {};
  33527. _gsDefine(ns, [], function(){ return func; }, global);
  33528. return func;
  33529. };
  33530. _gsDefine.globals = _globals;
  33531. /*
  33532. * ----------------------------------------------------------------
  33533. * Ease
  33534. * ----------------------------------------------------------------
  33535. */
  33536. var _baseParams = [0, 0, 1, 1],
  33537. _blankArray = [],
  33538. Ease = _class("easing.Ease", function(func, extraParams, type, power) {
  33539. this._func = func;
  33540. this._type = type || 0;
  33541. this._power = power || 0;
  33542. this._params = extraParams ? _baseParams.concat(extraParams) : _baseParams;
  33543. }, true),
  33544. _easeMap = Ease.map = {},
  33545. _easeReg = Ease.register = function(ease, names, types, create) {
  33546. var na = names.split(","),
  33547. i = na.length,
  33548. ta = (types || "easeIn,easeOut,easeInOut").split(","),
  33549. e, name, j, type;
  33550. while (--i > -1) {
  33551. name = na[i];
  33552. e = create ? _class("easing."+name, null, true) : gs.easing[name] || {};
  33553. j = ta.length;
  33554. while (--j > -1) {
  33555. type = ta[j];
  33556. _easeMap[name + "." + type] = _easeMap[type + name] = e[type] = ease.getRatio ? ease : ease[type] || new ease();
  33557. }
  33558. }
  33559. };
  33560. p = Ease.prototype;
  33561. p._calcEnd = false;
  33562. p.getRatio = function(p) {
  33563. if (this._func) {
  33564. this._params[0] = p;
  33565. return this._func.apply(null, this._params);
  33566. }
  33567. var t = this._type,
  33568. pw = this._power,
  33569. r = (t === 1) ? 1 - p : (t === 2) ? p : (p < 0.5) ? p * 2 : (1 - p) * 2;
  33570. if (pw === 1) {
  33571. r *= r;
  33572. } else if (pw === 2) {
  33573. r *= r * r;
  33574. } else if (pw === 3) {
  33575. r *= r * r * r;
  33576. } else if (pw === 4) {
  33577. r *= r * r * r * r;
  33578. }
  33579. return (t === 1) ? 1 - r : (t === 2) ? r : (p < 0.5) ? r / 2 : 1 - (r / 2);
  33580. };
  33581. //create all the standard eases like Linear, Quad, Cubic, Quart, Quint, Strong, Power0, Power1, Power2, Power3, and Power4 (each with easeIn, easeOut, and easeInOut)
  33582. a = ["Linear","Quad","Cubic","Quart","Quint,Strong"];
  33583. i = a.length;
  33584. while (--i > -1) {
  33585. p = a[i]+",Power"+i;
  33586. _easeReg(new Ease(null,null,1,i), p, "easeOut", true);
  33587. _easeReg(new Ease(null,null,2,i), p, "easeIn" + ((i === 0) ? ",easeNone" : ""));
  33588. _easeReg(new Ease(null,null,3,i), p, "easeInOut");
  33589. }
  33590. _easeMap.linear = gs.easing.Linear.easeIn;
  33591. _easeMap.swing = gs.easing.Quad.easeInOut; //for jQuery folks
  33592. /*
  33593. * ----------------------------------------------------------------
  33594. * EventDispatcher
  33595. * ----------------------------------------------------------------
  33596. */
  33597. var EventDispatcher = _class("events.EventDispatcher", function(target) {
  33598. this._listeners = {};
  33599. this._eventTarget = target || this;
  33600. });
  33601. p = EventDispatcher.prototype;
  33602. p.addEventListener = function(type, callback, scope, useParam, priority) {
  33603. priority = priority || 0;
  33604. var list = this._listeners[type],
  33605. index = 0,
  33606. listener, i;
  33607. if (list == null) {
  33608. this._listeners[type] = list = [];
  33609. }
  33610. i = list.length;
  33611. while (--i > -1) {
  33612. listener = list[i];
  33613. if (listener.c === callback && listener.s === scope) {
  33614. list.splice(i, 1);
  33615. } else if (index === 0 && listener.pr < priority) {
  33616. index = i + 1;
  33617. }
  33618. }
  33619. list.splice(index, 0, {c:callback, s:scope, up:useParam, pr:priority});
  33620. if (this === _ticker && !_tickerActive) {
  33621. _ticker.wake();
  33622. }
  33623. };
  33624. p.removeEventListener = function(type, callback) {
  33625. var list = this._listeners[type], i;
  33626. if (list) {
  33627. i = list.length;
  33628. while (--i > -1) {
  33629. if (list[i].c === callback) {
  33630. list.splice(i, 1);
  33631. return;
  33632. }
  33633. }
  33634. }
  33635. };
  33636. p.dispatchEvent = function(type) {
  33637. var list = this._listeners[type],
  33638. i, t, listener;
  33639. if (list) {
  33640. i = list.length;
  33641. t = this._eventTarget;
  33642. while (--i > -1) {
  33643. listener = list[i];
  33644. if (listener.up) {
  33645. listener.c.call(listener.s || t, {type:type, target:t});
  33646. } else {
  33647. listener.c.call(listener.s || t);
  33648. }
  33649. }
  33650. }
  33651. };
  33652. /*
  33653. * ----------------------------------------------------------------
  33654. * Ticker
  33655. * ----------------------------------------------------------------
  33656. */
  33657. var _reqAnimFrame = window.requestAnimationFrame,
  33658. _cancelAnimFrame = window.cancelAnimationFrame,
  33659. _getTime = Date.now || function() {return new Date().getTime();},
  33660. _lastUpdate = _getTime();
  33661. //now try to determine the requestAnimationFrame and cancelAnimationFrame functions and if none are found, we'll use a setTimeout()/clearTimeout() polyfill.
  33662. a = ["ms","moz","webkit","o"];
  33663. i = a.length;
  33664. while (--i > -1 && !_reqAnimFrame) {
  33665. _reqAnimFrame = window[a[i] + "RequestAnimationFrame"];
  33666. _cancelAnimFrame = window[a[i] + "CancelAnimationFrame"] || window[a[i] + "CancelRequestAnimationFrame"];
  33667. }
  33668. _class("Ticker", function(fps, useRAF) {
  33669. var _self = this,
  33670. _startTime = _getTime(),
  33671. _useRAF = (useRAF !== false && _reqAnimFrame),
  33672. _fps, _req, _id, _gap, _nextTime,
  33673. _tick = function(manual) {
  33674. _lastUpdate = _getTime();
  33675. _self.time = (_lastUpdate - _startTime) / 1000;
  33676. var overlap = _self.time - _nextTime,
  33677. dispatch;
  33678. if (!_fps || overlap > 0 || manual === true) {
  33679. _self.frame++;
  33680. _nextTime += overlap + (overlap >= _gap ? 0.004 : _gap - overlap);
  33681. dispatch = true;
  33682. }
  33683. if (manual !== true) { //make sure the request is made before we dispatch the "tick" event so that timing is maintained. Otherwise, if processing the "tick" requires a bunch of time (like 15ms) and we're using a setTimeout() that's based on 16.7ms, it'd technically take 31.7ms between frames otherwise.
  33684. _id = _req(_tick);
  33685. }
  33686. if (dispatch) {
  33687. _self.dispatchEvent("tick");
  33688. }
  33689. };
  33690. EventDispatcher.call(_self);
  33691. _self.time = _self.frame = 0;
  33692. _self.tick = function() {
  33693. _tick(true);
  33694. };
  33695. _self.sleep = function() {
  33696. if (_id == null) {
  33697. return;
  33698. }
  33699. if (!_useRAF || !_cancelAnimFrame) {
  33700. clearTimeout(_id);
  33701. } else {
  33702. _cancelAnimFrame(_id);
  33703. }
  33704. _req = _emptyFunc;
  33705. _id = null;
  33706. if (_self === _ticker) {
  33707. _tickerActive = false;
  33708. }
  33709. };
  33710. _self.wake = function() {
  33711. if (_id !== null) {
  33712. _self.sleep();
  33713. }
  33714. _req = (_fps === 0) ? _emptyFunc : (!_useRAF || !_reqAnimFrame) ? function(f) { return setTimeout(f, ((_nextTime - _self.time) * 1000 + 1) | 0); } : _reqAnimFrame;
  33715. if (_self === _ticker) {
  33716. _tickerActive = true;
  33717. }
  33718. _tick(2);
  33719. };
  33720. _self.fps = function(value) {
  33721. if (!arguments.length) {
  33722. return _fps;
  33723. }
  33724. _fps = value;
  33725. _gap = 1 / (_fps || 60);
  33726. _nextTime = this.time + _gap;
  33727. _self.wake();
  33728. };
  33729. _self.useRAF = function(value) {
  33730. if (!arguments.length) {
  33731. return _useRAF;
  33732. }
  33733. _self.sleep();
  33734. _useRAF = value;
  33735. _self.fps(_fps);
  33736. };
  33737. _self.fps(fps);
  33738. //a bug in iOS 6 Safari occasionally prevents the requestAnimationFrame from working initially, so we use a 1.5-second timeout that automatically falls back to setTimeout() if it senses this condition.
  33739. setTimeout(function() {
  33740. if (_useRAF && (!_id || _self.frame < 5)) {
  33741. _self.useRAF(false);
  33742. }
  33743. }, 1500);
  33744. });
  33745. p = gs.Ticker.prototype = new gs.events.EventDispatcher();
  33746. p.constructor = gs.Ticker;
  33747. /*
  33748. * ----------------------------------------------------------------
  33749. * Animation
  33750. * ----------------------------------------------------------------
  33751. */
  33752. var Animation = _class("core.Animation", function(duration, vars) {
  33753. this.vars = vars = vars || {};
  33754. this._duration = this._totalDuration = duration || 0;
  33755. this._delay = Number(vars.delay) || 0;
  33756. this._timeScale = 1;
  33757. this._active = (vars.immediateRender === true);
  33758. this.data = vars.data;
  33759. this._reversed = (vars.reversed === true);
  33760. if (!_rootTimeline) {
  33761. return;
  33762. }
  33763. if (!_tickerActive) { //some browsers (like iOS 6 Safari) shut down JavaScript execution when the tab is disabled and they [occasionally] neglect to start up requestAnimationFrame again when returning - this code ensures that the engine starts up again properly.
  33764. _ticker.wake();
  33765. }
  33766. var tl = this.vars.useFrames ? _rootFramesTimeline : _rootTimeline;
  33767. tl.add(this, tl._time);
  33768. if (this.vars.paused) {
  33769. this.paused(true);
  33770. }
  33771. });
  33772. _ticker = Animation.ticker = new gs.Ticker();
  33773. p = Animation.prototype;
  33774. p._dirty = p._gc = p._initted = p._paused = false;
  33775. p._totalTime = p._time = 0;
  33776. p._rawPrevTime = -1;
  33777. p._next = p._last = p._onUpdate = p._timeline = p.timeline = null;
  33778. p._paused = false;
  33779. //some browsers (like iOS) occasionally drop the requestAnimationFrame event when the user switches to a different tab and then comes back again, so we use a 2-second setTimeout() to sense if/when that condition occurs and then wake() the ticker.
  33780. var _checkTimeout = function() {
  33781. if (_tickerActive && _getTime() - _lastUpdate > 2000) {
  33782. _ticker.wake();
  33783. }
  33784. setTimeout(_checkTimeout, 2000);
  33785. };
  33786. _checkTimeout();
  33787. p.play = function(from, suppressEvents) {
  33788. if (arguments.length) {
  33789. this.seek(from, suppressEvents);
  33790. }
  33791. return this.reversed(false).paused(false);
  33792. };
  33793. p.pause = function(atTime, suppressEvents) {
  33794. if (arguments.length) {
  33795. this.seek(atTime, suppressEvents);
  33796. }
  33797. return this.paused(true);
  33798. };
  33799. p.resume = function(from, suppressEvents) {
  33800. if (arguments.length) {
  33801. this.seek(from, suppressEvents);
  33802. }
  33803. return this.paused(false);
  33804. };
  33805. p.seek = function(time, suppressEvents) {
  33806. return this.totalTime(Number(time), suppressEvents !== false);
  33807. };
  33808. p.restart = function(includeDelay, suppressEvents) {
  33809. return this.reversed(false).paused(false).totalTime(includeDelay ? -this._delay : 0, (suppressEvents !== false), true);
  33810. };
  33811. p.reverse = function(from, suppressEvents) {
  33812. if (arguments.length) {
  33813. this.seek((from || this.totalDuration()), suppressEvents);
  33814. }
  33815. return this.reversed(true).paused(false);
  33816. };
  33817. p.render = function(time, suppressEvents, force) {
  33818. //stub - we override this method in subclasses.
  33819. };
  33820. p.invalidate = function() {
  33821. return this;
  33822. };
  33823. p.isActive = function() {
  33824. var tl = this._timeline, //the 2 root timelines won't have a _timeline; they're always active.
  33825. startTime = this._startTime,
  33826. rawTime;
  33827. return (!tl || (!this._gc && !this._paused && tl.isActive() && (rawTime = tl.rawTime()) >= startTime && rawTime < startTime + this.totalDuration() / this._timeScale));
  33828. };
  33829. p._enabled = function (enabled, ignoreTimeline) {
  33830. if (!_tickerActive) {
  33831. _ticker.wake();
  33832. }
  33833. this._gc = !enabled;
  33834. this._active = this.isActive();
  33835. if (ignoreTimeline !== true) {
  33836. if (enabled && !this.timeline) {
  33837. this._timeline.add(this, this._startTime - this._delay);
  33838. } else if (!enabled && this.timeline) {
  33839. this._timeline._remove(this, true);
  33840. }
  33841. }
  33842. return false;
  33843. };
  33844. p._kill = function(vars, target) {
  33845. return this._enabled(false, false);
  33846. };
  33847. p.kill = function(vars, target) {
  33848. this._kill(vars, target);
  33849. return this;
  33850. };
  33851. p._uncache = function(includeSelf) {
  33852. var tween = includeSelf ? this : this.timeline;
  33853. while (tween) {
  33854. tween._dirty = true;
  33855. tween = tween.timeline;
  33856. }
  33857. return this;
  33858. };
  33859. p._swapSelfInParams = function(params) {
  33860. var i = params.length,
  33861. copy = params.concat();
  33862. while (--i > -1) {
  33863. if (params[i] === "{self}") {
  33864. copy[i] = this;
  33865. }
  33866. }
  33867. return copy;
  33868. };
  33869. //----Animation getters/setters --------------------------------------------------------
  33870. p.eventCallback = function(type, callback, params, scope) {
  33871. if ((type || "").substr(0,2) === "on") {
  33872. var v = this.vars;
  33873. if (arguments.length === 1) {
  33874. return v[type];
  33875. }
  33876. if (callback == null) {
  33877. delete v[type];
  33878. } else {
  33879. v[type] = callback;
  33880. v[type + "Params"] = (_isArray(params) && params.join("").indexOf("{self}") !== -1) ? this._swapSelfInParams(params) : params;
  33881. v[type + "Scope"] = scope;
  33882. }
  33883. if (type === "onUpdate") {
  33884. this._onUpdate = callback;
  33885. }
  33886. }
  33887. return this;
  33888. };
  33889. p.delay = function(value) {
  33890. if (!arguments.length) {
  33891. return this._delay;
  33892. }
  33893. if (this._timeline.smoothChildTiming) {
  33894. this.startTime( this._startTime + value - this._delay );
  33895. }
  33896. this._delay = value;
  33897. return this;
  33898. };
  33899. p.duration = function(value) {
  33900. if (!arguments.length) {
  33901. this._dirty = false;
  33902. return this._duration;
  33903. }
  33904. this._duration = this._totalDuration = value;
  33905. this._uncache(true); //true in case it's a TweenMax or TimelineMax that has a repeat - we'll need to refresh the totalDuration.
  33906. if (this._timeline.smoothChildTiming) if (this._time > 0) if (this._time < this._duration) if (value !== 0) {
  33907. this.totalTime(this._totalTime * (value / this._duration), true);
  33908. }
  33909. return this;
  33910. };
  33911. p.totalDuration = function(value) {
  33912. this._dirty = false;
  33913. return (!arguments.length) ? this._totalDuration : this.duration(value);
  33914. };
  33915. p.time = function(value, suppressEvents) {
  33916. if (!arguments.length) {
  33917. return this._time;
  33918. }
  33919. if (this._dirty) {
  33920. this.totalDuration();
  33921. }
  33922. return this.totalTime((value > this._duration) ? this._duration : value, suppressEvents);
  33923. };
  33924. p.totalTime = function(time, suppressEvents, uncapped) {
  33925. if (!_tickerActive) {
  33926. _ticker.wake();
  33927. }
  33928. if (!arguments.length) {
  33929. return this._totalTime;
  33930. }
  33931. if (this._timeline) {
  33932. if (time < 0 && !uncapped) {
  33933. time += this.totalDuration();
  33934. }
  33935. if (this._timeline.smoothChildTiming) {
  33936. if (this._dirty) {
  33937. this.totalDuration();
  33938. }
  33939. var totalDuration = this._totalDuration,
  33940. tl = this._timeline;
  33941. if (time > totalDuration && !uncapped) {
  33942. time = totalDuration;
  33943. }
  33944. this._startTime = (this._paused ? this._pauseTime : tl._time) - ((!this._reversed ? time : totalDuration - time) / this._timeScale);
  33945. if (!tl._dirty) { //for performance improvement. If the parent's cache is already dirty, it already took care of marking the ancestors as dirty too, so skip the function call here.
  33946. this._uncache(false);
  33947. }
  33948. //in case any of the ancestor timelines had completed but should now be enabled, we should reset their totalTime() which will also ensure that they're lined up properly and enabled. Skip for animations that are on the root (wasteful). Example: a TimelineLite.exportRoot() is performed when there's a paused tween on the root, the export will not complete until that tween is unpaused, but imagine a child gets restarted later, after all [unpaused] tweens have completed. The startTime of that child would get pushed out, but one of the ancestors may have completed.
  33949. if (tl._timeline) {
  33950. while (tl._timeline) {
  33951. if (tl._timeline._time !== (tl._startTime + tl._totalTime) / tl._timeScale) {
  33952. tl.totalTime(tl._totalTime, true);
  33953. }
  33954. tl = tl._timeline;
  33955. }
  33956. }
  33957. }
  33958. if (this._gc) {
  33959. this._enabled(true, false);
  33960. }
  33961. if (this._totalTime !== time || this._duration === 0) {
  33962. this.render(time, suppressEvents, false);
  33963. }
  33964. }
  33965. return this;
  33966. };
  33967. p.progress = p.totalProgress = function(value, suppressEvents) {
  33968. return (!arguments.length) ? this._time / this.duration() : this.totalTime(this.duration() * value, suppressEvents);
  33969. };
  33970. p.startTime = function(value) {
  33971. if (!arguments.length) {
  33972. return this._startTime;
  33973. }
  33974. if (value !== this._startTime) {
  33975. this._startTime = value;
  33976. if (this.timeline) if (this.timeline._sortChildren) {
  33977. this.timeline.add(this, value - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct.
  33978. }
  33979. }
  33980. return this;
  33981. };
  33982. p.timeScale = function(value) {
  33983. if (!arguments.length) {
  33984. return this._timeScale;
  33985. }
  33986. value = value || _tinyNum; //can't allow zero because it'll throw the math off
  33987. if (this._timeline && this._timeline.smoothChildTiming) {
  33988. var pauseTime = this._pauseTime,
  33989. t = (pauseTime || pauseTime === 0) ? pauseTime : this._timeline.totalTime();
  33990. this._startTime = t - ((t - this._startTime) * this._timeScale / value);
  33991. }
  33992. this._timeScale = value;
  33993. return this._uncache(false);
  33994. };
  33995. p.reversed = function(value) {
  33996. if (!arguments.length) {
  33997. return this._reversed;
  33998. }
  33999. if (value != this._reversed) {
  34000. this._reversed = value;
  34001. this.totalTime(this._totalTime, true);
  34002. }
  34003. return this;
  34004. };
  34005. p.paused = function(value) {
  34006. if (!arguments.length) {
  34007. return this._paused;
  34008. }
  34009. if (value != this._paused) if (this._timeline) {
  34010. if (!_tickerActive && !value) {
  34011. _ticker.wake();
  34012. }
  34013. var tl = this._timeline,
  34014. raw = tl.rawTime(),
  34015. elapsed = raw - this._pauseTime;
  34016. if (!value && tl.smoothChildTiming) {
  34017. this._startTime += elapsed;
  34018. this._uncache(false);
  34019. }
  34020. this._pauseTime = value ? raw : null;
  34021. this._paused = value;
  34022. this._active = this.isActive();
  34023. if (!value && elapsed !== 0 && this._initted && this.duration()) {
  34024. this.render((tl.smoothChildTiming ? this._totalTime : (raw - this._startTime) / this._timeScale), true, true); //in case the target's properties changed via some other tween or manual update by the user, we should force a render.
  34025. }
  34026. }
  34027. if (this._gc && !value) {
  34028. this._enabled(true, false);
  34029. }
  34030. return this;
  34031. };
  34032. /*
  34033. * ----------------------------------------------------------------
  34034. * SimpleTimeline
  34035. * ----------------------------------------------------------------
  34036. */
  34037. var SimpleTimeline = _class("core.SimpleTimeline", function(vars) {
  34038. Animation.call(this, 0, vars);
  34039. this.autoRemoveChildren = this.smoothChildTiming = true;
  34040. });
  34041. p = SimpleTimeline.prototype = new Animation();
  34042. p.constructor = SimpleTimeline;
  34043. p.kill()._gc = false;
  34044. p._first = p._last = null;
  34045. p._sortChildren = false;
  34046. p.add = p.insert = function(child, position, align, stagger) {
  34047. var prevTween, st;
  34048. child._startTime = Number(position || 0) + child._delay;
  34049. if (child._paused) if (this !== child._timeline) { //we only adjust the _pauseTime if it wasn't in this timeline already. Remember, sometimes a tween will be inserted again into the same timeline when its startTime is changed so that the tweens in the TimelineLite/Max are re-ordered properly in the linked list (so everything renders in the proper order).
  34050. child._pauseTime = child._startTime + ((this.rawTime() - child._startTime) / child._timeScale);
  34051. }
  34052. if (child.timeline) {
  34053. child.timeline._remove(child, true); //removes from existing timeline so that it can be properly added to this one.
  34054. }
  34055. child.timeline = child._timeline = this;
  34056. if (child._gc) {
  34057. child._enabled(true, true);
  34058. }
  34059. prevTween = this._last;
  34060. if (this._sortChildren) {
  34061. st = child._startTime;
  34062. while (prevTween && prevTween._startTime > st) {
  34063. prevTween = prevTween._prev;
  34064. }
  34065. }
  34066. if (prevTween) {
  34067. child._next = prevTween._next;
  34068. prevTween._next = child;
  34069. } else {
  34070. child._next = this._first;
  34071. this._first = child;
  34072. }
  34073. if (child._next) {
  34074. child._next._prev = child;
  34075. } else {
  34076. this._last = child;
  34077. }
  34078. child._prev = prevTween;
  34079. if (this._timeline) {
  34080. this._uncache(true);
  34081. }
  34082. return this;
  34083. };
  34084. p._remove = function(tween, skipDisable) {
  34085. if (tween.timeline === this) {
  34086. if (!skipDisable) {
  34087. tween._enabled(false, true);
  34088. }
  34089. tween.timeline = null;
  34090. if (tween._prev) {
  34091. tween._prev._next = tween._next;
  34092. } else if (this._first === tween) {
  34093. this._first = tween._next;
  34094. }
  34095. if (tween._next) {
  34096. tween._next._prev = tween._prev;
  34097. } else if (this._last === tween) {
  34098. this._last = tween._prev;
  34099. }
  34100. if (this._timeline) {
  34101. this._uncache(true);
  34102. }
  34103. }
  34104. return this;
  34105. };
  34106. p.render = function(time, suppressEvents, force) {
  34107. var tween = this._first,
  34108. next;
  34109. this._totalTime = this._time = this._rawPrevTime = time;
  34110. while (tween) {
  34111. next = tween._next; //record it here because the value could change after rendering...
  34112. if (tween._active || (time >= tween._startTime && !tween._paused)) {
  34113. if (!tween._reversed) {
  34114. tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
  34115. } else {
  34116. tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
  34117. }
  34118. }
  34119. tween = next;
  34120. }
  34121. };
  34122. p.rawTime = function() {
  34123. if (!_tickerActive) {
  34124. _ticker.wake();
  34125. }
  34126. return this._totalTime;
  34127. };
  34128. /*
  34129. * ----------------------------------------------------------------
  34130. * TweenLite
  34131. * ----------------------------------------------------------------
  34132. */
  34133. var TweenLite = _class("TweenLite", function(target, duration, vars) {
  34134. Animation.call(this, duration, vars);
  34135. this.render = TweenLite.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method)
  34136. if (target == null) {
  34137. throw "Cannot tween a null target.";
  34138. }
  34139. this.target = target = (typeof(target) !== "string") ? target : TweenLite.selector(target) || target;
  34140. var isSelector = (target.jquery || (target.length && target !== window && target[0] && (target[0] === window || (target[0].nodeType && target[0].style && !target.nodeType)))),
  34141. overwrite = this.vars.overwrite,
  34142. i, targ, targets;
  34143. this._overwrite = overwrite = (overwrite == null) ? _overwriteLookup[TweenLite.defaultOverwrite] : (typeof(overwrite) === "number") ? overwrite >> 0 : _overwriteLookup[overwrite];
  34144. if ((isSelector || target instanceof Array || (target.push && _isArray(target))) && typeof(target[0]) !== "number") {
  34145. this._targets = targets = _slice.call(target, 0);
  34146. this._propLookup = [];
  34147. this._siblings = [];
  34148. for (i = 0; i < targets.length; i++) {
  34149. targ = targets[i];
  34150. if (!targ) {
  34151. targets.splice(i--, 1);
  34152. continue;
  34153. } else if (typeof(targ) === "string") {
  34154. targ = targets[i--] = TweenLite.selector(targ); //in case it's an array of strings
  34155. if (typeof(targ) === "string") {
  34156. targets.splice(i+1, 1); //to avoid an endless loop (can't imagine why the selector would return a string, but just in case)
  34157. }
  34158. continue;
  34159. } else if (targ.length && targ !== window && targ[0] && (targ[0] === window || (targ[0].nodeType && targ[0].style && !targ.nodeType))) { //in case the user is passing in an array of selector objects (like jQuery objects), we need to check one more level and pull things out if necessary. Also note that <select> elements pass all the criteria regarding length and the first child having style, so we must also check to ensure the target isn't an HTML node itself.
  34160. targets.splice(i--, 1);
  34161. this._targets = targets = targets.concat(_slice.call(targ, 0));
  34162. continue;
  34163. }
  34164. this._siblings[i] = _register(targ, this, false);
  34165. if (overwrite === 1) if (this._siblings[i].length > 1) {
  34166. _applyOverwrite(targ, this, null, 1, this._siblings[i]);
  34167. }
  34168. }
  34169. } else {
  34170. this._propLookup = {};
  34171. this._siblings = _register(target, this, false);
  34172. if (overwrite === 1) if (this._siblings.length > 1) {
  34173. _applyOverwrite(target, this, null, 1, this._siblings);
  34174. }
  34175. }
  34176. if (this.vars.immediateRender || (duration === 0 && this._delay === 0 && this.vars.immediateRender !== false)) {
  34177. this.render(-this._delay, false, true);
  34178. }
  34179. }, true),
  34180. _isSelector = function(v) {
  34181. return (v.length && v !== window && v[0] && (v[0] === window || (v[0].nodeType && v[0].style && !v.nodeType))); //we cannot check "nodeType" if the target is window from within an iframe, otherwise it will trigger a security error in some browsers like Firefox.
  34182. },
  34183. _autoCSS = function(vars, target) {
  34184. var css = {},
  34185. p;
  34186. for (p in vars) {
  34187. if (!_reservedProps[p] && (!(p in target) || p === "x" || p === "y" || p === "width" || p === "height" || p === "className" || p === "border") && (!_plugins[p] || (_plugins[p] && _plugins[p]._autoCSS))) { //note: <img> elements contain read-only "x" and "y" properties. We should also prioritize editing css width/height rather than the element's properties.
  34188. css[p] = vars[p];
  34189. delete vars[p];
  34190. }
  34191. }
  34192. vars.css = css;
  34193. };
  34194. p = TweenLite.prototype = new Animation();
  34195. p.constructor = TweenLite;
  34196. p.kill()._gc = false;
  34197. //----TweenLite defaults, overwrite management, and root updates ----------------------------------------------------
  34198. p.ratio = 0;
  34199. p._firstPT = p._targets = p._overwrittenProps = p._startAt = null;
  34200. p._notifyPluginsOfEnabled = false;
  34201. TweenLite.version = "1.11.2";
  34202. TweenLite.defaultEase = p._ease = new Ease(null, null, 1, 1);
  34203. TweenLite.defaultOverwrite = "auto";
  34204. TweenLite.ticker = _ticker;
  34205. TweenLite.autoSleep = true;
  34206. TweenLite.selector = window.$ || window.jQuery || function(e) { if (window.$) { TweenLite.selector = window.$; return window.$(e); } return window.document ? window.document.getElementById((e.charAt(0) === "#") ? e.substr(1) : e) : e; };
  34207. var _internals = TweenLite._internals = {isArray:_isArray, isSelector:_isSelector}, //gives us a way to expose certain private values to other GreenSock classes without contaminating tha main TweenLite object.
  34208. _plugins = TweenLite._plugins = {},
  34209. _tweenLookup = TweenLite._tweenLookup = {},
  34210. _tweenLookupNum = 0,
  34211. _reservedProps = _internals.reservedProps = {ease:1, delay:1, overwrite:1, onComplete:1, onCompleteParams:1, onCompleteScope:1, useFrames:1, runBackwards:1, startAt:1, onUpdate:1, onUpdateParams:1, onUpdateScope:1, onStart:1, onStartParams:1, onStartScope:1, onReverseComplete:1, onReverseCompleteParams:1, onReverseCompleteScope:1, onRepeat:1, onRepeatParams:1, onRepeatScope:1, easeParams:1, yoyo:1, immediateRender:1, repeat:1, repeatDelay:1, data:1, paused:1, reversed:1, autoCSS:1},
  34212. _overwriteLookup = {none:0, all:1, auto:2, concurrent:3, allOnStart:4, preexisting:5, "true":1, "false":0},
  34213. _rootFramesTimeline = Animation._rootFramesTimeline = new SimpleTimeline(),
  34214. _rootTimeline = Animation._rootTimeline = new SimpleTimeline();
  34215. _rootTimeline._startTime = _ticker.time;
  34216. _rootFramesTimeline._startTime = _ticker.frame;
  34217. _rootTimeline._active = _rootFramesTimeline._active = true;
  34218. Animation._updateRoot = function() {
  34219. _rootTimeline.render((_ticker.time - _rootTimeline._startTime) * _rootTimeline._timeScale, false, false);
  34220. _rootFramesTimeline.render((_ticker.frame - _rootFramesTimeline._startTime) * _rootFramesTimeline._timeScale, false, false);
  34221. if (!(_ticker.frame % 120)) { //dump garbage every 120 frames...
  34222. var i, a, p;
  34223. for (p in _tweenLookup) {
  34224. a = _tweenLookup[p].tweens;
  34225. i = a.length;
  34226. while (--i > -1) {
  34227. if (a[i]._gc) {
  34228. a.splice(i, 1);
  34229. }
  34230. }
  34231. if (a.length === 0) {
  34232. delete _tweenLookup[p];
  34233. }
  34234. }
  34235. //if there are no more tweens in the root timelines, or if they're all paused, make the _timer sleep to reduce load on the CPU slightly
  34236. p = _rootTimeline._first;
  34237. if (!p || p._paused) if (TweenLite.autoSleep && !_rootFramesTimeline._first && _ticker._listeners.tick.length === 1) {
  34238. while (p && p._paused) {
  34239. p = p._next;
  34240. }
  34241. if (!p) {
  34242. _ticker.sleep();
  34243. }
  34244. }
  34245. }
  34246. };
  34247. _ticker.addEventListener("tick", Animation._updateRoot);
  34248. var _register = function(target, tween, scrub) {
  34249. var id = target._gsTweenID, a, i;
  34250. if (!_tweenLookup[id || (target._gsTweenID = id = "t" + (_tweenLookupNum++))]) {
  34251. _tweenLookup[id] = {target:target, tweens:[]};
  34252. }
  34253. if (tween) {
  34254. a = _tweenLookup[id].tweens;
  34255. a[(i = a.length)] = tween;
  34256. if (scrub) {
  34257. while (--i > -1) {
  34258. if (a[i] === tween) {
  34259. a.splice(i, 1);
  34260. }
  34261. }
  34262. }
  34263. }
  34264. return _tweenLookup[id].tweens;
  34265. },
  34266. _applyOverwrite = function(target, tween, props, mode, siblings) {
  34267. var i, changed, curTween, l;
  34268. if (mode === 1 || mode >= 4) {
  34269. l = siblings.length;
  34270. for (i = 0; i < l; i++) {
  34271. if ((curTween = siblings[i]) !== tween) {
  34272. if (!curTween._gc) if (curTween._enabled(false, false)) {
  34273. changed = true;
  34274. }
  34275. } else if (mode === 5) {
  34276. break;
  34277. }
  34278. }
  34279. return changed;
  34280. }
  34281. //NOTE: Add 0.0000000001 to overcome floating point errors that can cause the startTime to be VERY slightly off (when a tween's time() is set for example)
  34282. var startTime = tween._startTime + _tinyNum,
  34283. overlaps = [],
  34284. oCount = 0,
  34285. zeroDur = (tween._duration === 0),
  34286. globalStart;
  34287. i = siblings.length;
  34288. while (--i > -1) {
  34289. if ((curTween = siblings[i]) === tween || curTween._gc || curTween._paused) {
  34290. //ignore
  34291. } else if (curTween._timeline !== tween._timeline) {
  34292. globalStart = globalStart || _checkOverlap(tween, 0, zeroDur);
  34293. if (_checkOverlap(curTween, globalStart, zeroDur) === 0) {
  34294. overlaps[oCount++] = curTween;
  34295. }
  34296. } else if (curTween._startTime <= startTime) if (curTween._startTime + curTween.totalDuration() / curTween._timeScale + _tinyNum > startTime) if (!((zeroDur || !curTween._initted) && startTime - curTween._startTime <= 0.0000000002)) {
  34297. overlaps[oCount++] = curTween;
  34298. }
  34299. }
  34300. i = oCount;
  34301. while (--i > -1) {
  34302. curTween = overlaps[i];
  34303. if (mode === 2) if (curTween._kill(props, target)) {
  34304. changed = true;
  34305. }
  34306. if (mode !== 2 || (!curTween._firstPT && curTween._initted)) {
  34307. if (curTween._enabled(false, false)) { //if all property tweens have been overwritten, kill the tween.
  34308. changed = true;
  34309. }
  34310. }
  34311. }
  34312. return changed;
  34313. },
  34314. _checkOverlap = function(tween, reference, zeroDur) {
  34315. var tl = tween._timeline,
  34316. ts = tl._timeScale,
  34317. t = tween._startTime;
  34318. while (tl._timeline) {
  34319. t += tl._startTime;
  34320. ts *= tl._timeScale;
  34321. if (tl._paused) {
  34322. return -100;
  34323. }
  34324. tl = tl._timeline;
  34325. }
  34326. t /= ts;
  34327. return (t > reference) ? t - reference : ((zeroDur && t === reference) || (!tween._initted && t - reference < 2 * _tinyNum)) ? _tinyNum : ((t += tween.totalDuration() / tween._timeScale / ts) > reference + _tinyNum) ? 0 : t - reference - _tinyNum;
  34328. };
  34329. //---- TweenLite instance methods -----------------------------------------------------------------------------
  34330. p._init = function() {
  34331. var v = this.vars,
  34332. op = this._overwrittenProps,
  34333. dur = this._duration,
  34334. immediate = v.immediateRender,
  34335. ease = v.ease,
  34336. i, initPlugins, pt, p;
  34337. if (v.startAt) {
  34338. if (this._startAt) {
  34339. this._startAt.render(-1, true); //if we've run a startAt previously (when the tween instantiated), we should revert it so that the values re-instantiate correctly particularly for relative tweens. Without this, a TweenLite.fromTo(obj, 1, {x:"+=100"}, {x:"-=100"}), for example, would actually jump to +=200 because the startAt would run twice, doubling the relative change.
  34340. }
  34341. v.startAt.overwrite = 0;
  34342. v.startAt.immediateRender = true;
  34343. this._startAt = TweenLite.to(this.target, 0, v.startAt);
  34344. if (immediate) {
  34345. if (this._time > 0) {
  34346. this._startAt = null; //tweens that render immediately (like most from() and fromTo() tweens) shouldn't revert when their parent timeline's playhead goes backward past the startTime because the initial render could have happened anytime and it shouldn't be directly correlated to this tween's startTime. Imagine setting up a complex animation where the beginning states of various objects are rendered immediately but the tween doesn't happen for quite some time - if we revert to the starting values as soon as the playhead goes backward past the tween's startTime, it will throw things off visually. Reversion should only happen in TimelineLite/Max instances where immediateRender was false (which is the default in the convenience methods like from()).
  34347. } else if (dur !== 0) {
  34348. return; //we skip initialization here so that overwriting doesn't occur until the tween actually begins. Otherwise, if you create several immediateRender:true tweens of the same target/properties to drop into a TimelineLite or TimelineMax, the last one created would overwrite the first ones because they didn't get placed into the timeline yet before the first render occurs and kicks in overwriting.
  34349. }
  34350. }
  34351. } else if (v.runBackwards && dur !== 0) {
  34352. //from() tweens must be handled uniquely: their beginning values must be rendered but we don't want overwriting to occur yet (when time is still 0). Wait until the tween actually begins before doing all the routines like overwriting. At that time, we should render at the END of the tween to ensure that things initialize correctly (remember, from() tweens go backwards)
  34353. if (this._startAt) {
  34354. this._startAt.render(-1, true);
  34355. this._startAt = null;
  34356. } else {
  34357. pt = {};
  34358. for (p in v) { //copy props into a new object and skip any reserved props, otherwise onComplete or onUpdate or onStart could fire. We should, however, permit autoCSS to go through.
  34359. if (!_reservedProps[p] || p === "autoCSS") {
  34360. pt[p] = v[p];
  34361. }
  34362. }
  34363. pt.overwrite = 0;
  34364. pt.data = "isFromStart"; //we tag the tween with as "isFromStart" so that if [inside a plugin] we need to only do something at the very END of a tween, we have a way of identifying this tween as merely the one that's setting the beginning values for a "from()" tween. For example, clearProps in CSSPlugin should only get applied at the very END of a tween and without this tag, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in.
  34365. this._startAt = TweenLite.to(this.target, 0, pt);
  34366. if (!v.immediateRender) {
  34367. this._startAt.render(-1, true); //for tweens that aren't rendered immediately, we still need to use the _startAt to record the starting values so that we can revert to them if the parent timeline's playhead goes backward beyond the beginning, but we immediately revert the tween back otherwise the parent tween that's currently instantiating wouldn't see the wrong starting values (since they were changed by the _startAt tween)
  34368. } else if (this._time === 0) {
  34369. return;
  34370. }
  34371. }
  34372. }
  34373. if (!ease) {
  34374. this._ease = TweenLite.defaultEase;
  34375. } else if (ease instanceof Ease) {
  34376. this._ease = (v.easeParams instanceof Array) ? ease.config.apply(ease, v.easeParams) : ease;
  34377. } else {
  34378. this._ease = (typeof(ease) === "function") ? new Ease(ease, v.easeParams) : _easeMap[ease] || TweenLite.defaultEase;
  34379. }
  34380. this._easeType = this._ease._type;
  34381. this._easePower = this._ease._power;
  34382. this._firstPT = null;
  34383. if (this._targets) {
  34384. i = this._targets.length;
  34385. while (--i > -1) {
  34386. if ( this._initProps( this._targets[i], (this._propLookup[i] = {}), this._siblings[i], (op ? op[i] : null)) ) {
  34387. initPlugins = true;
  34388. }
  34389. }
  34390. } else {
  34391. initPlugins = this._initProps(this.target, this._propLookup, this._siblings, op);
  34392. }
  34393. if (initPlugins) {
  34394. TweenLite._onPluginEvent("_onInitAllProps", this); //reorders the array in order of priority. Uses a static TweenPlugin method in order to minimize file size in TweenLite
  34395. }
  34396. if (op) if (!this._firstPT) if (typeof(this.target) !== "function") { //if all tweening properties have been overwritten, kill the tween. If the target is a function, it's probably a delayedCall so let it live.
  34397. this._enabled(false, false);
  34398. }
  34399. if (v.runBackwards) {
  34400. pt = this._firstPT;
  34401. while (pt) {
  34402. pt.s += pt.c;
  34403. pt.c = -pt.c;
  34404. pt = pt._next;
  34405. }
  34406. }
  34407. this._onUpdate = v.onUpdate;
  34408. this._initted = true;
  34409. };
  34410. p._initProps = function(target, propLookup, siblings, overwrittenProps) {
  34411. var p, i, initPlugins, plugin, a, pt, v;
  34412. if (target == null) {
  34413. return false;
  34414. }
  34415. if (!this.vars.css) if (target.style) if (target !== window && target.nodeType) if (_plugins.css) if (this.vars.autoCSS !== false) { //it's so common to use TweenLite/Max to animate the css of DOM elements, we assume that if the target is a DOM element, that's what is intended (a convenience so that users don't have to wrap things in css:{}, although we still recommend it for a slight performance boost and better specificity). Note: we cannot check "nodeType" on the window inside an iframe.
  34416. _autoCSS(this.vars, target);
  34417. }
  34418. for (p in this.vars) {
  34419. v = this.vars[p];
  34420. if (_reservedProps[p]) {
  34421. if (v) if ((v instanceof Array) || (v.push && _isArray(v))) if (v.join("").indexOf("{self}") !== -1) {
  34422. this.vars[p] = v = this._swapSelfInParams(v, this);
  34423. }
  34424. } else if (_plugins[p] && (plugin = new _plugins[p]())._onInitTween(target, this.vars[p], this)) {
  34425. //t - target [object]
  34426. //p - property [string]
  34427. //s - start [number]
  34428. //c - change [number]
  34429. //f - isFunction [boolean]
  34430. //n - name [string]
  34431. //pg - isPlugin [boolean]
  34432. //pr - priority [number]
  34433. this._firstPT = pt = {_next:this._firstPT, t:plugin, p:"setRatio", s:0, c:1, f:true, n:p, pg:true, pr:plugin._priority};
  34434. i = plugin._overwriteProps.length;
  34435. while (--i > -1) {
  34436. propLookup[plugin._overwriteProps[i]] = this._firstPT;
  34437. }
  34438. if (plugin._priority || plugin._onInitAllProps) {
  34439. initPlugins = true;
  34440. }
  34441. if (plugin._onDisable || plugin._onEnable) {
  34442. this._notifyPluginsOfEnabled = true;
  34443. }
  34444. } else {
  34445. this._firstPT = propLookup[p] = pt = {_next:this._firstPT, t:target, p:p, f:(typeof(target[p]) === "function"), n:p, pg:false, pr:0};
  34446. pt.s = (!pt.f) ? parseFloat(target[p]) : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ]();
  34447. pt.c = (typeof(v) === "string" && v.charAt(1) === "=") ? parseInt(v.charAt(0) + "1", 10) * Number(v.substr(2)) : (Number(v) - pt.s) || 0;
  34448. }
  34449. if (pt) if (pt._next) {
  34450. pt._next._prev = pt;
  34451. }
  34452. }
  34453. if (overwrittenProps) if (this._kill(overwrittenProps, target)) { //another tween may have tried to overwrite properties of this tween before init() was called (like if two tweens start at the same time, the one created second will run first)
  34454. return this._initProps(target, propLookup, siblings, overwrittenProps);
  34455. }
  34456. if (this._overwrite > 1) if (this._firstPT) if (siblings.length > 1) if (_applyOverwrite(target, this, propLookup, this._overwrite, siblings)) {
  34457. this._kill(propLookup, target);
  34458. return this._initProps(target, propLookup, siblings, overwrittenProps);
  34459. }
  34460. return initPlugins;
  34461. };
  34462. p.render = function(time, suppressEvents, force) {
  34463. var prevTime = this._time,
  34464. duration = this._duration,
  34465. isComplete, callback, pt, rawPrevTime;
  34466. if (time >= duration) {
  34467. this._totalTime = this._time = duration;
  34468. this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1;
  34469. if (!this._reversed) {
  34470. isComplete = true;
  34471. callback = "onComplete";
  34472. }
  34473. if (duration === 0) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
  34474. rawPrevTime = this._rawPrevTime;
  34475. if (time === 0 || rawPrevTime < 0 || rawPrevTime === _tinyNum) if (rawPrevTime !== time) {
  34476. force = true;
  34477. if (rawPrevTime > _tinyNum) {
  34478. callback = "onReverseComplete";
  34479. }
  34480. }
  34481. this._rawPrevTime = rawPrevTime = (!suppressEvents || time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  34482. }
  34483. } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
  34484. this._totalTime = this._time = 0;
  34485. this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
  34486. if (prevTime !== 0 || (duration === 0 && this._rawPrevTime > _tinyNum)) {
  34487. callback = "onReverseComplete";
  34488. isComplete = this._reversed;
  34489. }
  34490. if (time < 0) {
  34491. this._active = false;
  34492. if (duration === 0) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
  34493. if (this._rawPrevTime >= 0) {
  34494. force = true;
  34495. }
  34496. this._rawPrevTime = rawPrevTime = (!suppressEvents || time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  34497. }
  34498. } else if (!this._initted) { //if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately.
  34499. force = true;
  34500. }
  34501. } else {
  34502. this._totalTime = this._time = time;
  34503. if (this._easeType) {
  34504. var r = time / duration, type = this._easeType, pow = this._easePower;
  34505. if (type === 1 || (type === 3 && r >= 0.5)) {
  34506. r = 1 - r;
  34507. }
  34508. if (type === 3) {
  34509. r *= 2;
  34510. }
  34511. if (pow === 1) {
  34512. r *= r;
  34513. } else if (pow === 2) {
  34514. r *= r * r;
  34515. } else if (pow === 3) {
  34516. r *= r * r * r;
  34517. } else if (pow === 4) {
  34518. r *= r * r * r * r;
  34519. }
  34520. if (type === 1) {
  34521. this.ratio = 1 - r;
  34522. } else if (type === 2) {
  34523. this.ratio = r;
  34524. } else if (time / duration < 0.5) {
  34525. this.ratio = r / 2;
  34526. } else {
  34527. this.ratio = 1 - (r / 2);
  34528. }
  34529. } else {
  34530. this.ratio = this._ease.getRatio(time / duration);
  34531. }
  34532. }
  34533. if (this._time === prevTime && !force) {
  34534. return;
  34535. } else if (!this._initted) {
  34536. this._init();
  34537. if (!this._initted || this._gc) { //immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example.
  34538. return;
  34539. }
  34540. //_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently.
  34541. if (this._time && !isComplete) {
  34542. this.ratio = this._ease.getRatio(this._time / duration);
  34543. } else if (isComplete && this._ease._calcEnd) {
  34544. this.ratio = this._ease.getRatio((this._time === 0) ? 0 : 1);
  34545. }
  34546. }
  34547. if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) {
  34548. this._active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done.
  34549. }
  34550. if (prevTime === 0) {
  34551. if (this._startAt) {
  34552. if (time >= 0) {
  34553. this._startAt.render(time, suppressEvents, force);
  34554. } else if (!callback) {
  34555. callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area.
  34556. }
  34557. }
  34558. if (this.vars.onStart) if (this._time !== 0 || duration === 0) if (!suppressEvents) {
  34559. this.vars.onStart.apply(this.vars.onStartScope || this, this.vars.onStartParams || _blankArray);
  34560. }
  34561. }
  34562. pt = this._firstPT;
  34563. while (pt) {
  34564. if (pt.f) {
  34565. pt.t[pt.p](pt.c * this.ratio + pt.s);
  34566. } else {
  34567. pt.t[pt.p] = pt.c * this.ratio + pt.s;
  34568. }
  34569. pt = pt._next;
  34570. }
  34571. if (this._onUpdate) {
  34572. if (time < 0) if (this._startAt && this._startTime) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
  34573. this._startAt.render(time, suppressEvents, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete.
  34574. }
  34575. if (!suppressEvents) if (!(force && this._time === 0 && prevTime === 0)) {
  34576. this._onUpdate.apply(this.vars.onUpdateScope || this, this.vars.onUpdateParams || _blankArray);
  34577. }
  34578. }
  34579. if (callback) if (!this._gc) { //check _gc because there's a chance that kill() could be called in an onUpdate
  34580. if (time < 0 && this._startAt && !this._onUpdate && this._startTime) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
  34581. this._startAt.render(time, suppressEvents, force);
  34582. }
  34583. if (isComplete) {
  34584. if (this._timeline.autoRemoveChildren) {
  34585. this._enabled(false, false);
  34586. }
  34587. this._active = false;
  34588. }
  34589. if (!suppressEvents && this.vars[callback]) {
  34590. this.vars[callback].apply(this.vars[callback + "Scope"] || this, this.vars[callback + "Params"] || _blankArray);
  34591. }
  34592. if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) { //the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless.
  34593. this._rawPrevTime = 0;
  34594. }
  34595. }
  34596. };
  34597. p._kill = function(vars, target) {
  34598. if (vars === "all") {
  34599. vars = null;
  34600. }
  34601. if (vars == null) if (target == null || target === this.target) {
  34602. return this._enabled(false, false);
  34603. }
  34604. target = (typeof(target) !== "string") ? (target || this._targets || this.target) : TweenLite.selector(target) || target;
  34605. var i, overwrittenProps, p, pt, propLookup, changed, killProps, record;
  34606. if ((_isArray(target) || _isSelector(target)) && typeof(target[0]) !== "number") {
  34607. i = target.length;
  34608. while (--i > -1) {
  34609. if (this._kill(vars, target[i])) {
  34610. changed = true;
  34611. }
  34612. }
  34613. } else {
  34614. if (this._targets) {
  34615. i = this._targets.length;
  34616. while (--i > -1) {
  34617. if (target === this._targets[i]) {
  34618. propLookup = this._propLookup[i] || {};
  34619. this._overwrittenProps = this._overwrittenProps || [];
  34620. overwrittenProps = this._overwrittenProps[i] = vars ? this._overwrittenProps[i] || {} : "all";
  34621. break;
  34622. }
  34623. }
  34624. } else if (target !== this.target) {
  34625. return false;
  34626. } else {
  34627. propLookup = this._propLookup;
  34628. overwrittenProps = this._overwrittenProps = vars ? this._overwrittenProps || {} : "all";
  34629. }
  34630. if (propLookup) {
  34631. killProps = vars || propLookup;
  34632. record = (vars !== overwrittenProps && overwrittenProps !== "all" && vars !== propLookup && (typeof(vars) !== "object" || !vars._tempKill)); //_tempKill is a super-secret way to delete a particular tweening property but NOT have it remembered as an official overwritten property (like in BezierPlugin)
  34633. for (p in killProps) {
  34634. if ((pt = propLookup[p])) {
  34635. if (pt.pg && pt.t._kill(killProps)) {
  34636. changed = true; //some plugins need to be notified so they can perform cleanup tasks first
  34637. }
  34638. if (!pt.pg || pt.t._overwriteProps.length === 0) {
  34639. if (pt._prev) {
  34640. pt._prev._next = pt._next;
  34641. } else if (pt === this._firstPT) {
  34642. this._firstPT = pt._next;
  34643. }
  34644. if (pt._next) {
  34645. pt._next._prev = pt._prev;
  34646. }
  34647. pt._next = pt._prev = null;
  34648. }
  34649. delete propLookup[p];
  34650. }
  34651. if (record) {
  34652. overwrittenProps[p] = 1;
  34653. }
  34654. }
  34655. if (!this._firstPT && this._initted) { //if all tweening properties are killed, kill the tween. Without this line, if there's a tween with multiple targets and then you killTweensOf() each target individually, the tween would technically still remain active and fire its onComplete even though there aren't any more properties tweening.
  34656. this._enabled(false, false);
  34657. }
  34658. }
  34659. }
  34660. return changed;
  34661. };
  34662. p.invalidate = function() {
  34663. if (this._notifyPluginsOfEnabled) {
  34664. TweenLite._onPluginEvent("_onDisable", this);
  34665. }
  34666. this._firstPT = null;
  34667. this._overwrittenProps = null;
  34668. this._onUpdate = null;
  34669. this._startAt = null;
  34670. this._initted = this._active = this._notifyPluginsOfEnabled = false;
  34671. this._propLookup = (this._targets) ? {} : [];
  34672. return this;
  34673. };
  34674. p._enabled = function(enabled, ignoreTimeline) {
  34675. if (!_tickerActive) {
  34676. _ticker.wake();
  34677. }
  34678. if (enabled && this._gc) {
  34679. var targets = this._targets,
  34680. i;
  34681. if (targets) {
  34682. i = targets.length;
  34683. while (--i > -1) {
  34684. this._siblings[i] = _register(targets[i], this, true);
  34685. }
  34686. } else {
  34687. this._siblings = _register(this.target, this, true);
  34688. }
  34689. }
  34690. Animation.prototype._enabled.call(this, enabled, ignoreTimeline);
  34691. if (this._notifyPluginsOfEnabled) if (this._firstPT) {
  34692. return TweenLite._onPluginEvent((enabled ? "_onEnable" : "_onDisable"), this);
  34693. }
  34694. return false;
  34695. };
  34696. //----TweenLite static methods -----------------------------------------------------
  34697. TweenLite.to = function(target, duration, vars) {
  34698. return new TweenLite(target, duration, vars);
  34699. };
  34700. TweenLite.from = function(target, duration, vars) {
  34701. vars.runBackwards = true;
  34702. vars.immediateRender = (vars.immediateRender != false);
  34703. return new TweenLite(target, duration, vars);
  34704. };
  34705. TweenLite.fromTo = function(target, duration, fromVars, toVars) {
  34706. toVars.startAt = fromVars;
  34707. toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
  34708. return new TweenLite(target, duration, toVars);
  34709. };
  34710. TweenLite.delayedCall = function(delay, callback, params, scope, useFrames) {
  34711. return new TweenLite(callback, 0, {delay:delay, onComplete:callback, onCompleteParams:params, onCompleteScope:scope, onReverseComplete:callback, onReverseCompleteParams:params, onReverseCompleteScope:scope, immediateRender:false, useFrames:useFrames, overwrite:0});
  34712. };
  34713. TweenLite.set = function(target, vars) {
  34714. return new TweenLite(target, 0, vars);
  34715. };
  34716. TweenLite.getTweensOf = function(target, onlyActive) {
  34717. if (target == null) { return []; }
  34718. target = (typeof(target) !== "string") ? target : TweenLite.selector(target) || target;
  34719. var i, a, j, t;
  34720. if ((_isArray(target) || _isSelector(target)) && typeof(target[0]) !== "number") {
  34721. i = target.length;
  34722. a = [];
  34723. while (--i > -1) {
  34724. a = a.concat(TweenLite.getTweensOf(target[i], onlyActive));
  34725. }
  34726. i = a.length;
  34727. //now get rid of any duplicates (tweens of arrays of objects could cause duplicates)
  34728. while (--i > -1) {
  34729. t = a[i];
  34730. j = i;
  34731. while (--j > -1) {
  34732. if (t === a[j]) {
  34733. a.splice(i, 1);
  34734. }
  34735. }
  34736. }
  34737. } else {
  34738. a = _register(target).concat();
  34739. i = a.length;
  34740. while (--i > -1) {
  34741. if (a[i]._gc || (onlyActive && !a[i].isActive())) {
  34742. a.splice(i, 1);
  34743. }
  34744. }
  34745. }
  34746. return a;
  34747. };
  34748. TweenLite.killTweensOf = TweenLite.killDelayedCallsTo = function(target, onlyActive, vars) {
  34749. if (typeof(onlyActive) === "object") {
  34750. vars = onlyActive; //for backwards compatibility (before "onlyActive" parameter was inserted)
  34751. onlyActive = false;
  34752. }
  34753. var a = TweenLite.getTweensOf(target, onlyActive),
  34754. i = a.length;
  34755. while (--i > -1) {
  34756. a[i]._kill(vars, target);
  34757. }
  34758. };
  34759. /*
  34760. * ----------------------------------------------------------------
  34761. * TweenPlugin (could easily be split out as a separate file/class, but included for ease of use (so that people don't need to include another <script> call before loading plugins which is easy to forget)
  34762. * ----------------------------------------------------------------
  34763. */
  34764. var TweenPlugin = _class("plugins.TweenPlugin", function(props, priority) {
  34765. this._overwriteProps = (props || "").split(",");
  34766. this._propName = this._overwriteProps[0];
  34767. this._priority = priority || 0;
  34768. this._super = TweenPlugin.prototype;
  34769. }, true);
  34770. p = TweenPlugin.prototype;
  34771. TweenPlugin.version = "1.10.1";
  34772. TweenPlugin.API = 2;
  34773. p._firstPT = null;
  34774. p._addTween = function(target, prop, start, end, overwriteProp, round) {
  34775. var c, pt;
  34776. if (end != null && (c = (typeof(end) === "number" || end.charAt(1) !== "=") ? Number(end) - start : parseInt(end.charAt(0) + "1", 10) * Number(end.substr(2)))) {
  34777. this._firstPT = pt = {_next:this._firstPT, t:target, p:prop, s:start, c:c, f:(typeof(target[prop]) === "function"), n:overwriteProp || prop, r:round};
  34778. if (pt._next) {
  34779. pt._next._prev = pt;
  34780. }
  34781. return pt;
  34782. }
  34783. };
  34784. p.setRatio = function(v) {
  34785. var pt = this._firstPT,
  34786. min = 0.000001,
  34787. val;
  34788. while (pt) {
  34789. val = pt.c * v + pt.s;
  34790. if (pt.r) {
  34791. val = (val + ((val > 0) ? 0.5 : -0.5)) | 0; //about 4x faster than Math.round()
  34792. } else if (val < min) if (val > -min) { //prevents issues with converting very small numbers to strings in the browser
  34793. val = 0;
  34794. }
  34795. if (pt.f) {
  34796. pt.t[pt.p](val);
  34797. } else {
  34798. pt.t[pt.p] = val;
  34799. }
  34800. pt = pt._next;
  34801. }
  34802. };
  34803. p._kill = function(lookup) {
  34804. var a = this._overwriteProps,
  34805. pt = this._firstPT,
  34806. i;
  34807. if (lookup[this._propName] != null) {
  34808. this._overwriteProps = [];
  34809. } else {
  34810. i = a.length;
  34811. while (--i > -1) {
  34812. if (lookup[a[i]] != null) {
  34813. a.splice(i, 1);
  34814. }
  34815. }
  34816. }
  34817. while (pt) {
  34818. if (lookup[pt.n] != null) {
  34819. if (pt._next) {
  34820. pt._next._prev = pt._prev;
  34821. }
  34822. if (pt._prev) {
  34823. pt._prev._next = pt._next;
  34824. pt._prev = null;
  34825. } else if (this._firstPT === pt) {
  34826. this._firstPT = pt._next;
  34827. }
  34828. }
  34829. pt = pt._next;
  34830. }
  34831. return false;
  34832. };
  34833. p._roundProps = function(lookup, value) {
  34834. var pt = this._firstPT;
  34835. while (pt) {
  34836. if (lookup[this._propName] || (pt.n != null && lookup[ pt.n.split(this._propName + "_").join("") ])) { //some properties that are very plugin-specific add a prefix named after the _propName plus an underscore, so we need to ignore that extra stuff here.
  34837. pt.r = value;
  34838. }
  34839. pt = pt._next;
  34840. }
  34841. };
  34842. TweenLite._onPluginEvent = function(type, tween) {
  34843. var pt = tween._firstPT,
  34844. changed, pt2, first, last, next;
  34845. if (type === "_onInitAllProps") {
  34846. //sorts the PropTween linked list in order of priority because some plugins need to render earlier/later than others, like MotionBlurPlugin applies its effects after all x/y/alpha tweens have rendered on each frame.
  34847. while (pt) {
  34848. next = pt._next;
  34849. pt2 = first;
  34850. while (pt2 && pt2.pr > pt.pr) {
  34851. pt2 = pt2._next;
  34852. }
  34853. if ((pt._prev = pt2 ? pt2._prev : last)) {
  34854. pt._prev._next = pt;
  34855. } else {
  34856. first = pt;
  34857. }
  34858. if ((pt._next = pt2)) {
  34859. pt2._prev = pt;
  34860. } else {
  34861. last = pt;
  34862. }
  34863. pt = next;
  34864. }
  34865. pt = tween._firstPT = first;
  34866. }
  34867. while (pt) {
  34868. if (pt.pg) if (typeof(pt.t[type]) === "function") if (pt.t[type]()) {
  34869. changed = true;
  34870. }
  34871. pt = pt._next;
  34872. }
  34873. return changed;
  34874. };
  34875. TweenPlugin.activate = function(plugins) {
  34876. var i = plugins.length;
  34877. while (--i > -1) {
  34878. if (plugins[i].API === TweenPlugin.API) {
  34879. _plugins[(new plugins[i]())._propName] = plugins[i];
  34880. }
  34881. }
  34882. return true;
  34883. };
  34884. //provides a more concise way to define plugins that have no dependencies besides TweenPlugin and TweenLite, wrapping common boilerplate stuff into one function (added in 1.9.0). You don't NEED to use this to define a plugin - the old way still works and can be useful in certain (rare) situations.
  34885. _gsDefine.plugin = function(config) {
  34886. if (!config || !config.propName || !config.init || !config.API) { throw "illegal plugin definition."; }
  34887. var propName = config.propName,
  34888. priority = config.priority || 0,
  34889. overwriteProps = config.overwriteProps,
  34890. map = {init:"_onInitTween", set:"setRatio", kill:"_kill", round:"_roundProps", initAll:"_onInitAllProps"},
  34891. Plugin = _class("plugins." + propName.charAt(0).toUpperCase() + propName.substr(1) + "Plugin",
  34892. function() {
  34893. TweenPlugin.call(this, propName, priority);
  34894. this._overwriteProps = overwriteProps || [];
  34895. }, (config.global === true)),
  34896. p = Plugin.prototype = new TweenPlugin(propName),
  34897. prop;
  34898. p.constructor = Plugin;
  34899. Plugin.API = config.API;
  34900. for (prop in map) {
  34901. if (typeof(config[prop]) === "function") {
  34902. p[map[prop]] = config[prop];
  34903. }
  34904. }
  34905. Plugin.version = config.version;
  34906. TweenPlugin.activate([Plugin]);
  34907. return Plugin;
  34908. };
  34909. //now run through all the dependencies discovered and if any are missing, log that to the console as a warning. This is why it's best to have TweenLite load last - it can check all the dependencies for you.
  34910. a = window._gsQueue;
  34911. if (a) {
  34912. for (i = 0; i < a.length; i++) {
  34913. a[i]();
  34914. }
  34915. for (p in _defLookup) {
  34916. if (!_defLookup[p].func) {
  34917. window.console.log("GSAP encountered missing dependency: com.greensock." + p);
  34918. }
  34919. }
  34920. }
  34921. _tickerActive = false; //ensures that the first official animation forces a ticker.tick() to update the time when it is instantiated
  34922. })(window);
  34923. /**
  34924. * User: qzix13
  34925. * Date: 27.12.13
  34926. */
  34927. function LevelMng(app) {
  34928. app.levelMng = this;
  34929. this.app = app;
  34930. this.total = LevelMng.levels.length;
  34931. this.tutorial = null;
  34932. var curr = cookie.get('lc');
  34933. this.curr = curr || 1;
  34934. }
  34935. LevelMng.prototype.create = function (level) {
  34936. level = level || this.curr;
  34937. if (level < 1) level = 1;
  34938. else if (level > this.total) level = 1;//this.total;
  34939. this.curr = level;
  34940. cookie.set('lc', level.toString());
  34941. level--;
  34942. var levelData = LevelMng.levels[level];
  34943. var clicks = levelData.clicks;
  34944. var bubbles = levelData.bubbles;
  34945. var n = bubbles.length;
  34946. /*var i = 0;
  34947. var j = 0;
  34948. var b;
  34949. for (i = 0; i < this.app.playState.rows; i++) {
  34950. for (j = 0; j < this.app.playState.cols; j++) {
  34951. new Bubble(this.app, j, i, this.app.phaser.rnd.integerInRange(0, 4));
  34952. }
  34953. }*/
  34954. for (var i = 0; i < n; i++) {
  34955. var col = bubbles[i].c;
  34956. var row = bubbles[i].r;
  34957. var index = bubbles[i].i;
  34958. new Bubble(this.app, col, row, index);
  34959. }
  34960. this.app.playState.resetLevelData(this.curr, clicks);
  34961. if (level === 0) {
  34962. if (this.tutorial) {
  34963. this.tutorial.destroy();
  34964. this.tutorial = null;
  34965. }
  34966. this.tutorial = this.app.phaser.add.child(this.app.playState.gameLayer,
  34967. this.app.playState.cellSize * 3 - this.app.playState.cellSize / 2,
  34968. this.app.playState.cellSize * 4 - this.app.playState.cellSize / 2, 'txt_atlas');
  34969. this.tutorial.frameName = 'txt_tutorial';
  34970. this.tutorial.anchor.setTo(.5, .5);
  34971. this.tutorial.scale.setTo(0.8, 0.8);
  34972. }
  34973. };
  34974. LevelMng.prototype.destroy = function () {
  34975. if (this.app.playState === null) return;
  34976. var i = 0, n = 0;
  34977. var bubbles = this.app.playState._bubbles;
  34978. var bullets = this.app.playState._bullets;
  34979. for (i = 0, n = bubbles.length; i < n; i++) {
  34980. bubbles[i].destroy();
  34981. }
  34982. bubbles.splice(0, n);
  34983. for (i = 0, n = bullets.length; i < n; i++) {
  34984. bullets[i].stop();
  34985. }
  34986. if (this.tutorial) {
  34987. this.tutorial.destroy();
  34988. this.tutorial = null;
  34989. }
  34990. };
  34991. LevelMng.prototype.next = function () {
  34992. this.destroy();
  34993. this.create(++this.curr);
  34994. };
  34995. LevelMng.levels = [
  34996. /** Description
  34997. * clicks - За яку максимальну к-сть кліків необхідно пройти левел.
  34998. * bubbles - масив із розташування та розмірами шариків.
  34999. * c - (col) колонка (0-4).
  35000. * r - (row) рядок (0-5).
  35001. * i - (index) Індекс розміру шарика (0-3).
  35002. * */
  35003. /* 1 */ { clicks: 1, bubbles: [ { c:2, r: 2, i:3 } ] },
  35004. /* 2 */ { clicks: 1, bubbles: [ { c:1, r: 3, i:3 }, { c:3, r: 3, i:3 } ] },
  35005. /* 3 */ { clicks: 1, bubbles: [ { c:2, r: 1, i:3 }, { c:2, r: 2, i:3 }, { c:2, r: 3, i:2 }, { c:2, r: 4, i:3 } ] },
  35006. /* 4 */ { clicks: 2, bubbles: [ { c:0, r: 2, i:3 }, { c:0, r: 3, i:2 }, { c:2, r: 2, i:2 }, { c:2, r: 3, i:3 }, { c:4, r: 2, i:3 }, { c:4, r: 3, i:2 } ] },
  35007. /* 5 */ { clicks: 1, bubbles: [ { c:1, r: 1, i:3 }, { c:1, r: 3, i:2 }, { c:1, r: 5, i:2 }, { c:2, r: 1, i:3 }, { c:2, r: 3, i:1 }, { c:2, r: 5, i:3 }, { c:3, r: 1, i:3 }, { c:3, r: 3, i:3 }, { c:3, r: 5, i:2 } ] },
  35008. /* 6 */ { clicks: 1, bubbles: [ { c:1, r: 1, i:3 }, { c:1, r: 2, i:2 }, { c:1, r: 3, i:3 }, { c:1, r: 4, i:3 }, { c:2, r: 1, i:1 }, { c:2, r: 4, i:2 }, { c:3, r: 1, i:3 }, { c:3, r: 2, i:2 }, { c:3, r: 3, i:3 }, { c:3, r: 4, i:3 } ] },
  35009. /* 7 */ { clicks: 2, bubbles: [ { c:0, r: 0, i:2 }, { c:0, r: 1, i:3 }, { c:0, r: 2, i:2 }, { c:0, r: 4, i:3 }, { c:0, r: 5, i:2 }, { c:1, r: 2, i:3 }, { c:1, r: 3, i:1 }, { c:1, r: 4, i:3 }, { c:3, r: 2, i:3 }, { c:3, r: 3, i:1 }, { c:3, r: 4, i:3 }, { c:4, r: 0, i:2 }, { c:4, r: 1, i:3 }, { c:4, r: 2, i:2 }, { c:4, r: 4, i:3 }, { c:4, r: 5, i:2 } ] },
  35010. /* 8 */ { clicks: 3, bubbles: [ { c:0, r: 3, i:2 }, { c:1, r: 0, i:3 }, { c:1, r: 3, i:3 }, { c:1, r: 4, i:1 }, { c:2, r: 0, i:1 }, { c:2, r: 1, i:2 }, { c:2, r: 3, i:0 }, { c:2, r: 4, i:3 }, { c:2, r: 5, i:3 }, { c:3, r: 0, i:3 }, { c:3, r: 3, i:3 }, { c:3, r: 4, i:2 }, { c:4, r: 3, i:2 } ] },
  35011. /* 9 */ { clicks: 2, bubbles: [ { c:1, r: 1, i:2 }, { c:1, r: 2, i:1 }, { c:1, r: 4, i:3 }, { c:1, r: 5, i:1 }, { c:2, r: 1, i:3 }, { c:2, r: 2, i:3 }, { c:2, r: 4, i:2 }, { c:2, r: 5, i:3 }, { c:3, r: 1, i:2 }, { c:3, r: 2, i:1 }, { c:3, r: 4, i:3 }, { c:3, r: 5, i:1 } ] },
  35012. /* 10 */ { clicks: 2, bubbles: [ { c:0, r: 0, i:3 }, { c:0, r: 2, i:2 }, { c:0, r: 3, i:1 }, { c:1, r: 1, i:3 }, { c:1, r: 4, i:3 }, { c:2, r: 1, i:2 }, { c:2, r: 2, i:3 }, { c:2, r: 3, i:3 }, { c:2, r: 4, i:0 }, { c:2, r: 5, i:3 }, { c:3, r: 1, i:3 }, { c:3, r: 4, i:3 }, { c:4, r: 0, i:3 }, { c:4, r: 2, i:1 }, { c:4, r: 3, i:2 } ] },
  35013. /* 11 */ { clicks: 4, bubbles: [ { c:1, r: 1, i:2 }, { c:1, r: 4, i:3 }, { c:2, r: 0, i:2 }, { c:2, r: 1, i:1 }, { c:2, r: 2, i:2 }, { c:2, r: 3, i:3 }, { c:2, r: 4, i:0 }, { c:2, r: 5, i:3 }, { c:3, r: 1, i:2 }, { c:3, r: 4, i:3 } ] },
  35014. /* 12 */ { clicks: 3, bubbles: [ { c:0, r: 1, i:2 }, { c:0, r: 3, i:3 }, { c:0, r: 5, i:2 }, { c:1, r: 0, i:3 }, { c:1, r: 2, i:3 }, { c:1, r: 4, i:1 }, { c:2, r: 1, i:0 }, { c:2, r: 3, i:3 }, { c:2, r: 5, i:3 }, { c:3, r: 0, i:3 }, { c:3, r: 2, i:3 }, { c:3, r: 4, i:1 }, { c:4, r: 1, i:2 }, { c:4, r: 3, i:3 }, { c:4, r: 5, i:2 } ] },
  35015. /* 13 */ { clicks: 2, bubbles: [ { c:0, r: 1, i:2 }, { c:0, r: 4, i:3 }, { c:1, r: 0, i:3 }, { c:1, r: 1, i:2 }, { c:1, r: 3, i:3 }, { c:1, r: 4, i:0 }, { c:1, r: 5, i:2 }, { c:2, r: 0, i:2 }, { c:2, r: 1, i:3 }, { c:2, r: 2, i:2 }, { c:2, r: 3, i:3 }, { c:3, r: 0, i:1 }, { c:3, r: 1, i:2 }, { c:3, r: 3, i:3 }, { c:3, r: 4, i:0 }, { c:3, r: 5, i:2 }, { c:4, r: 1, i:3 }, { c:4, r: 4, i:3 } ] },
  35016. /* 14 */ { clicks: 3, bubbles: [ { c:0, r: 0, i:2 }, { c:0, r: 5, i:2 }, { c:1, r: 0, i:2 }, { c:1, r: 1, i:2 }, { c:1, r: 2, i:2 }, { c:1, r: 3, i:2 }, { c:1, r: 4, i:2 }, { c:1, r: 5, i:2 }, { c:2, r: 2, i:1 }, { c:2, r: 3, i:3 }, { c:3, r: 0, i:2 }, { c:3, r: 1, i:2 }, { c:3, r: 2, i:2 }, { c:3, r: 3, i:2 }, { c:3, r: 4, i:2 }, { c:3, r: 5, i:2 }, { c:4, r: 0, i:2 }, { c:4, r: 5, i:2 } ] },
  35017. /* 15 */ { clicks: 3, bubbles: [ { c:0, r: 1, i:3 }, { c:0, r: 2, i:2 }, { c:0, r: 3, i:3 }, { c:0, r: 4, i:3 }, { c:0, r: 5, i:1 }, { c:1, r: 1, i:2 }, { c:1, r: 2, i:1 }, { c:1, r: 5, i:3 }, { c:2, r: 1, i:1 }, { c:2, r: 3, i:2 }, { c:2, r: 5, i:3 }, { c:3, r: 1, i:3 }, { c:3, r: 4, i:0 }, { c:3, r: 5, i:2 }, { c:4, r: 1, i:2 }, { c:4, r: 2, i:2 }, { c:4, r: 3, i:3 }, { c:4, r: 4, i:2 }, { c:4, r: 5, i:1 } ] },
  35018. /* 16 */ { clicks: 3, bubbles: [ { c:0, r: 0, i:3 }, { c:0, r: 1, i:2 }, { c:0, r: 2, i:1 }, { c:0, r: 3, i:0 }, { c:1, r: 0, i:0 }, { c:1, r: 2, i:3 }, { c:1, r: 5, i:3 }, { c:2, r: 0, i:2 }, { c:2, r: 1, i:2 }, { c:2, r: 2, i:3 }, { c:2, r: 3, i:1 }, { c:2, r: 4, i:2 }, { c:2, r: 5, i:3 }, { c:3, r: 0, i:0 }, { c:3, r: 2, i:3 }, { c:3, r: 5, i:3 }, { c:4, r: 0, i:3 }, { c:4, r: 1, i:2 }, { c:4, r: 2, i:1 }, { c:4, r: 3, i:0 } ] },
  35019. /* 17 */ { clicks: 5, bubbles: [ { c:0, r: 0, i:2 }, { c:0, r: 2, i:2 }, { c:0, r: 3, i:1 }, { c:0, r: 5, i:2 }, { c:1, r: 1, i:3 }, { c:1, r: 4, i:3 }, { c:2, r: 2, i:2 }, { c:2, r: 3, i:3 }, { c:3, r: 1, i:3 }, { c:3, r: 4, i:2 }, { c:4, r: 0, i:3 }, { c:4, r: 2, i:1 }, { c:4, r: 3, i:0 }, { c:4, r: 5, i:3 } ] },
  35020. /* 18 */ { clicks: 4, bubbles: [ { c:0, r: 2, i:1 }, { c:0, r: 3, i:2 }, { c:1, r: 1, i:2 }, { c:1, r: 2, i:0 }, { c:1, r: 3, i:3 }, { c:1, r: 4, i:2 }, { c:2, r: 0, i:2 }, { c:2, r: 1, i:3 }, { c:2, r: 4, i:3 }, { c:2, r: 5, i:2 }, { c:3, r: 1, i:2 }, { c:3, r: 2, i:3 }, { c:3, r: 3, i:2 }, { c:3, r: 4, i:2 }, { c:4, r: 2, i:0 }, { c:4, r: 3, i:1 } ] },
  35021. /* 19 */ { clicks: 5, bubbles: [ { c:0, r: 1, i:2 }, { c:0, r: 2, i:1 }, { c:1, r: 0, i:2 }, { c:1, r: 2, i:1 }, { c:1, r: 3, i:2 }, { c:1, r: 4, i:3 }, { c:1, r: 5, i:2 }, { c:2, r: 1, i:2 }, { c:2, r: 3, i:3 }, { c:2, r: 4, i:0 }, { c:3, r: 0, i:2 }, { c:3, r: 2, i:1 }, { c:3, r: 3, i:2 }, { c:3, r: 4, i:3 }, { c:3, r: 5, i:2 }, { c:4, r: 1, i:2 }, { c:4, r: 2, i:1 } ] },
  35022. /* 20 */ { clicks: 4, bubbles: [ { c:0, r: 0, i:2 }, { c:0, r: 5, i:3 }, { c:1, r: 0, i:1 }, { c:1, r: 1, i:2 }, { c:1, r: 4, i:2 }, { c:1, r: 5, i:1 }, { c:2, r: 0, i:2 }, { c:2, r: 1, i:3 }, { c:2, r: 2, i:0 }, { c:2, r: 3, i:2 }, { c:2, r: 4, i:3 }, { c:2, r: 5, i:2 }, { c:3, r: 0, i:1 }, { c:3, r: 1, i:2 }, { c:3, r: 4, i:1 }, { c:3, r: 5, i:0 }, { c:4, r: 0, i:2 }, { c:4, r: 5, i:3 } ] },
  35023. /* 21 */ { clicks: 5, bubbles: [ { c:0, r: 1, i:2 }, { c:0, r: 3, i:3 }, { c:1, r: 0, i:2 }, { c:1, r: 1, i:1 }, { c:1, r: 2, i:2 }, { c:1, r: 3, i:0 }, { c:1, r: 4, i:3 }, { c:2, r: 1, i:2 }, { c:2, r: 3, i:3 }, { c:3, r: 0, i:2 }, { c:3, r: 1, i:0 }, { c:3, r: 2, i:3 }, { c:3, r: 3, i:1 }, { c:3, r: 4, i:3 }, { c:4, r: 1, i:2 }, { c:4, r: 3, i:3 } ] },
  35024. /* 22 */ { clicks: 6, bubbles: [ { c:0, r: 0, i:3 }, { c:0, r: 4, i:3 }, { c:0, r: 5, i:1 }, { c:1, r: 2, i:2 }, { c:1, r: 3, i:1 }, { c:1, r: 4, i:3 }, { c:2, r: 0, i:0 }, { c:2, r: 1, i:1 }, { c:2, r: 2, i:2 }, { c:2, r: 3, i:1 }, { c:2, r: 4, i:3 }, { c:2, r: 5, i:1 }, { c:3, r: 2, i:2 }, { c:3, r: 3, i:1 }, { c:3, r: 4, i:3 }, { c:4, r: 0, i:3 }, { c:4, r: 4, i:3 }, { c:4, r: 5, i:1 } ] },
  35025. /* 23 */ { clicks: 6, bubbles: [ { c:0, r: 1, i:2 }, { c:0, r: 2, i:3 }, { c:0, r: 5, i:2 }, { c:1, r: 2, i:0 }, { c:1, r: 3, i:3 }, { c:1, r: 4, i:2 }, { c:2, r: 0, i:2 }, { c:2, r: 1, i:3 }, { c:2, r: 5, i:1 }, { c:3, r: 2, i:0 }, { c:3, r: 3, i:3 }, { c:3, r: 4, i:2 }, { c:4, r: 1, i:2 }, { c:4, r: 2, i:3 }, { c:4, r: 5, i:2 } ] },
  35026. /* 24 */ { clicks: 4, bubbles: [ { c:0, r: 0, i:2 }, { c:0, r: 1, i:2 }, { c:0, r: 2, i:2 }, { c:0, r: 3, i:2 }, { c:1, r: 0, i:2 }, { c:1, r: 2, i:1 }, { c:1, r: 4, i:3 }, { c:1, r: 5, i:2 }, { c:2, r: 0, i:2 }, { c:2, r: 3, i:0 }, { c:2, r: 4, i:3 }, { c:2, r: 5, i:2 }, { c:3, r: 0, i:2 }, { c:3, r: 2, i:1 }, { c:3, r: 4, i:3 }, { c:3, r: 5, i:2 }, { c:4, r: 0, i:2 }, { c:4, r: 1, i:2 }, { c:4, r: 2, i:2 }, { c:4, r: 3, i:2 } ] },
  35027. /* 25 */ { clicks: 4, bubbles: [ { c:0, r: 0, i:3 }, { c:0, r: 3, i:2 }, { c:0, r: 4, i:2 }, { c:0, r: 5, i:3 }, { c:1, r: 1, i:1 }, { c:1, r: 3, i:3 }, { c:1, r: 5, i:2 }, { c:2, r: 0, i:2 }, { c:2, r: 2, i:1 }, { c:2, r: 3, i:2 }, { c:2, r: 5, i:0 }, { c:3, r: 1, i:1 }, { c:3, r: 3, i:3 }, { c:3, r: 5, i:2 }, { c:4, r: 0, i:3 }, { c:4, r: 3, i:2 }, { c:4, r: 4, i:2 }, { c:4, r: 5, i:3 } ] },
  35028. /* 26 */ { clicks: 4, bubbles: [ { c:0, r: 0, i:2 }, { c:0, r: 1, i:2 }, { c:0, r: 4, i:3 }, { c:0, r: 5, i:1 }, { c:1, r: 1, i:3 }, { c:1, r: 2, i:2 }, { c:1, r: 3, i:2 }, { c:1, r: 4, i:0 }, { c:2, r: 2, i:1 }, { c:2, r: 3, i:2 }, { c:3, r: 1, i:0 }, { c:3, r: 2, i:2 }, { c:3, r: 3, i:2 }, { c:3, r: 4, i:3 }, { c:4, r: 0, i:1 }, { c:4, r: 1, i:3 }, { c:4, r: 4, i:2 }, { c:4, r: 5, i:2 } ] },
  35029. /* 27 */ { clicks: 5, bubbles: [ { c:0, r: 0, i:2 }, { c:0, r: 2, i:1 }, { c:0, r: 4, i:2 }, { c:1, r: 0, i:3 }, { c:1, r: 2, i:3 }, { c:1, r: 4, i:1 }, { c:2, r: 0, i:1 }, { c:2, r: 1, i:2 }, { c:2, r: 2, i:1 }, { c:2, r: 3, i:2 }, { c:2, r: 4, i:1 }, { c:2, r: 5, i:3 }, { c:3, r: 0, i:3 }, { c:3, r: 2, i:3 }, { c:3, r: 4, i:1 }, { c:4, r: 0, i:2 }, { c:4, r: 2, i:1 }, { c:4, r: 4, i:2 } ] },
  35030. /* 28 */ { clicks: 5, bubbles: [ { c:0, r: 0, i:1 }, { c:0, r: 4, i:2 }, { c:0, r: 5, i:2 }, { c:1, r: 0, i:3 }, { c:1, r: 2, i:1 }, { c:1, r: 3, i:3 }, { c:1, r: 5, i:1 }, { c:2, r: 2, i:2 }, { c:2, r: 5, i:2 }, { c:3, r: 0, i:1 }, { c:3, r: 2, i:3 }, { c:3, r: 3, i:2 }, { c:3, r: 5, i:0 }, { c:4, r: 0, i:3 }, { c:4, r: 4, i:1 }, { c:4, r: 5, i:3 } ] },
  35031. /* 29 */ { clicks: 5, bubbles: [ { c:0, r: 0, i:2 }, { c:0, r: 5, i:2 }, { c:1, r: 0, i:2 }, { c:1, r: 1, i:2 }, { c:1, r: 2, i:2 }, { c:1, r: 4, i:2 }, { c:2, r: 1, i:2 }, { c:2, r: 2, i:0 }, { c:2, r: 4, i:2 }, { c:2, r: 5, i:2 }, { c:3, r: 0, i:2 }, { c:3, r: 1, i:2 }, { c:3, r: 2, i:2 }, { c:3, r: 4, i:2 }, { c:4, r: 0, i:2 }, { c:4, r: 5, i:2 } ] },
  35032. /* 30 */ { clicks: 3, bubbles: [ { c:0, r: 3, i:3 }, { c:1, r: 0, i:3 }, { c:1, r: 1, i:3 }, { c:1, r: 2, i:0 }, { c:1, r: 3, i:3 }, { c:1, r: 4, i:3 }, { c:1, r: 5, i:0 }, { c:2, r: 0, i:3 }, { c:2, r: 1, i:0 }, { c:2, r: 4, i:0 }, { c:2, r: 5, i:3 }, { c:3, r: 0, i:0 }, { c:3, r: 1, i:3 }, { c:3, r: 2, i:3 }, { c:3, r: 3, i:0 }, { c:3, r: 4, i:3 }, { c:3, r: 5, i:3 }, { c:4, r: 2, i:3 } ] },
  35033. ];
  35034. /**
  35035. * User: qzix13
  35036. * Date: 27.12.13
  35037. */
  35038. function MenuState(app) {
  35039. this.app = app;
  35040. this.app.menuState = this;
  35041. this.windowWidth = 520;
  35042. this.windowHeight = 700;
  35043. this.canvas = app.phaser.add.group(app.phaser.world, 'menu_state_canvas');
  35044. this.bg = app.phaser.add.tileSprite(0, 0, 640, 960, 'bg');
  35045. this.canvas.add(this.bg);
  35046. this.mainLayer = app.phaser.add.group(this.canvas);
  35047. this.canvas.add(app.bgOver._container);
  35048. this.flowers = app.phaser.add.sprite(this.windowWidth / 1.95, this.windowHeight / 2.2, 'flowers');
  35049. this.flowers.anchor.setTo(0.5, 0.5);
  35050. this.flowers.scale.setTo(0.8, 0.8);
  35051. this.mainLayer.add(this.flowers);
  35052. this.gameName = app.phaser.add.child(this.mainLayer, 0, 0, 'game_name');
  35053. this.gameName.anchor.setTo(0.5, 0.5);
  35054. this.gameName.scale.setTo(0.85, 0.85);
  35055. this.gameName.x = this.windowWidth / 2;
  35056. this.gameName.y = 120;
  35057. /*this.spilLogo = app.phaser.add.child(this.mainLayer, 0, 0, 'logo_l');
  35058. //this.spilLogo.frameName = 'logo_m';
  35059. this.spilLogo.anchor.setTo(.5, .5);
  35060. this.spilLogo.scale.setTo(.6, .6);
  35061. this.spilLogo.x = this.spilLogo.width / 2 + 10;
  35062. this.spilLogo.y = this.spilLogo.height / 2 + 15;
  35063. this.spilLogo.inputEnabled = true;
  35064. this.spilLogo.events.onInputDown.add(function() { app.gotoSponsor(); });*/
  35065. var scale = 0.65;
  35066. this.btnMusic = app.phaser.add.button(this.windowWidth - 110, 40, 'game_atlas', this.onBtnMusicClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35067. this.btnMusic.scale.setTo(scale, scale);
  35068. this.btnMusic.anchor.setTo(.5, .5);
  35069. this.mainLayer.add(this.btnMusic);
  35070. this.icoMusic = app.phaser.add.child(this.mainLayer, this.btnMusic.x, this.btnMusic.y, 'game_atlas');
  35071. this.icoMusic.frameName = this.app.isMusic ? 'ico_music' : 'ico_music_off';
  35072. this.icoMusic.anchor.setTo(.5, .5);
  35073. this.icoMusic.scale.x = this.icoMusic.scale.y = scale - 0.2;
  35074. this.btnSound = app.phaser.add.button(this.windowWidth - 45, 40, 'game_atlas', this.onBtnSoundClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35075. this.btnSound.scale.setTo(scale, scale);
  35076. this.btnSound.anchor.setTo(.5, .5);
  35077. this.mainLayer.add(this.btnSound);
  35078. this.icoSound = app.phaser.add.child(this.mainLayer, this.btnSound.x, this.btnSound.y, 'game_atlas');
  35079. this.icoSound.frameName = this.app.isSound ? 'ico_sound' : 'ico_sound_off';
  35080. this.icoSound.anchor.setTo(.5, .5);
  35081. this.icoSound.scale.x = this.icoSound.scale.y = scale - 0.15;
  35082. scale = 0.9;
  35083. this.btnPlay = app.phaser.add.button(this.windowWidth / 2, this.windowHeight / 1.8, 'button_play', this.onBtnPlayClick, this, 2, 0, 1);
  35084. this.btnPlay.scale.setTo(scale, scale);
  35085. this.btnPlay.anchor.setTo(.5, .5);
  35086. this.mainLayer.add(this.btnPlay);
  35087. scale -= 0.04;
  35088. this.twBtnPlay = app.phaser.add.tween(this.btnPlay.scale).to( { x: scale, y: scale }, 400, null, true, 0.0, 100000, true);
  35089. scale = 0.8;
  35090. this.btnInfo = app.phaser.add.button(this.btnPlay.x - 150, this.btnPlay.y + 150, 'game_atlas', this.onBtnInfoClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35091. this.btnInfo.scale.setTo(scale, scale);
  35092. this.btnInfo.anchor.setTo(.5, .5);
  35093. this.mainLayer.add(this.btnInfo);
  35094. this.btnInfo.visible = false;
  35095. this.icoInfo = app.phaser.add.child(this.mainLayer, this.btnInfo.x, this.btnInfo.y, 'game_atlas');
  35096. this.icoInfo.frameName = 'ico_info';
  35097. this.icoInfo.anchor.setTo(.5, .5);
  35098. this.icoInfo.scale.x = this.icoInfo.scale.y = scale - 0.15;
  35099. this.icoInfo.visible = false;
  35100. this.btnReset = app.phaser.add.button(this.btnPlay.x + 150, this.btnPlay.y + 150, 'game_atlas', this.onBtnResetClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35101. this.btnReset.scale.setTo(scale, scale);
  35102. this.btnReset.anchor.setTo(.5, .5);
  35103. this.mainLayer.add(this.btnReset);
  35104. this.icoReset = app.phaser.add.child(this.mainLayer, this.btnReset.x, this.btnReset.y, 'game_atlas');
  35105. this.icoReset.frameName = 'ico_reset';
  35106. this.icoReset.anchor.setTo(.5, .5);
  35107. this.icoReset.scale.x = this.icoReset.scale.y = scale - 0.15;
  35108. this.btnMoreGames = app.phaser.add.button(this.btnPlay.x, this.btnPlay.y + 150, 'button_more_games', app.gotoSponsor, this, 2, 0, 1);
  35109. this.btnMoreGames.scale.setTo(scale, scale);
  35110. this.btnMoreGames.anchor.setTo(.5, .5);
  35111. this.mainLayer.add(this.btnMoreGames);
  35112. this.creditsGroup = app.phaser.add.group(this.mainLayer);
  35113. this.bgCredits = app.phaser.add.child(this.creditsGroup, 0, 0, 'bg_credits');
  35114. this.bgCredits.inputEnabled = true;
  35115. this.creditsGroup.x = (this.windowWidth - this.bgCredits.width) / 2;
  35116. this.creditsYInScreen = this.creditsGroup.y = (this.windowHeight - this.bgCredits.height) / 2;
  35117. this.creditsYOutScreen = -this.bgCredits.height;
  35118. this.btnCreditsClose = app.phaser.add.button(this.bgCredits.width / 2, this.bgCredits.height + 15, 'game_atlas', this.onBtnCreditsCloseClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35119. this.btnCreditsClose.scale.setTo(scale, scale);
  35120. this.btnCreditsClose.anchor.setTo(.5, .5);
  35121. this.creditsGroup.add(this.btnCreditsClose);
  35122. this.txtCreditsOk = app.phaser.add.bitmapText(this.btnCreditsClose.x - 2, this.btnCreditsClose.y + 4, this.app.texts.btnOk, { font: '36px HoboText', align: 'center' });
  35123. this.txtCreditsOk.anchor.setTo(.5, .5);
  35124. this.creditsGroup.add(this.txtCreditsOk);
  35125. this.creditsGroup.visible = false;
  35126. this.clearGroup = app.phaser.add.group(this.mainLayer);
  35127. this.bgClear = app.phaser.add.child(this.clearGroup, 0, 0, 'bg_clear');
  35128. this.bgClear.inputEnabled = true;
  35129. this.bgClear.scale.setTo(0.9, 0.9);
  35130. this.clearGroup.x = (this.windowWidth - this.bgClear.width) / 2;
  35131. this.clearYInScreen = this.clearGroup.y = (this.windowHeight - this.bgClear.height) / 2;
  35132. this.clearYOutScreen = -this.bgClear.height;
  35133. scale = 0.7;
  35134. this.btnClearYes = app.phaser.add.button(this.bgClear.width / 4, this.bgClear.height / 1.3, 'game_atlas', this.onBtnClearYesClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35135. this.btnClearYes.scale.setTo(scale, scale);
  35136. this.btnClearYes.anchor.setTo(.5, .5);
  35137. this.clearGroup.add(this.btnClearYes);
  35138. this.txtClearYes = app.phaser.add.bitmapText(this.btnClearYes.x - 2, this.btnClearYes.y + 4, this.app.texts.btnYes, { font: '40px HoboText', align: 'center' });
  35139. this.txtClearYes.anchor.setTo(.5, .5);
  35140. this.txtClearYes.scale.copyFrom(this.btnClearYes.scale);
  35141. this.clearGroup.add(this.txtClearYes);
  35142. this.btnClearNo = app.phaser.add.button(this.bgClear.width / 1.3, this.bgClear.height / 1.3, 'game_atlas', this.onBtnClearNoClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35143. this.btnClearNo.scale.setTo(scale, scale);
  35144. this.btnClearNo.anchor.setTo(.5, .5);
  35145. this.clearGroup.add(this.btnClearNo);
  35146. this.txtClearNo = app.phaser.add.bitmapText(this.btnClearNo.x - 2, this.btnClearNo.y + 4, this.app.texts.btnNo, { font: '40px HoboText', align: 'center' });
  35147. this.txtClearNo.anchor.setTo(.5, .5);
  35148. this.txtClearNo.scale.copyFrom(this.btnClearNo.scale);
  35149. this.clearGroup.add(this.txtClearNo);
  35150. this.clearGroup.visible = false;
  35151. var txtScale = 0.8;
  35152. this.txtScore = app.phaser.add.child(this.mainLayer, 10, this.windowHeight - 30, 'txt_atlas');
  35153. this.txtScore.frameName = 'txt_score';
  35154. this.txtScore.anchor.setTo(.0,.5);
  35155. this.txtScore.scale.setTo(txtScale, txtScale);
  35156. console.log('========================', this.txtScore.width)
  35157. this.txtScoreValue = app.phaser.add.bitmapText(this.txtScore.x + this.txtScore.width, this.txtScore.y + 1, '0', { font: '26px HoboDigits', align: 'left' });
  35158. this.txtScoreValue.anchor.setTo(.0, .5);
  35159. this.txtScoreValue.setText(app.getTotalScore().toString());
  35160. this.mainLayer.add(this.txtScoreValue);
  35161. };
  35162. MenuState.prototype.destroy = function () {
  35163. this.app.menuState = null;
  35164. this.app = null;
  35165. this.twBtnPlay.stop();
  35166. this.twBtnPlay = null;
  35167. this.canvas.destroy();
  35168. this.canvas = null;
  35169. this.bg.destroy();
  35170. this.bg = null;
  35171. this.flowers.destroy();
  35172. this.flowers = null;
  35173. this.mainLayer.destroy();
  35174. this.mainLayer = null;
  35175. this.gameName.destroy();
  35176. this.gameName = null;
  35177. /*this.spilLogo.destroy();
  35178. this.spilLogo = null;*/
  35179. this.btnMusic.destroy();
  35180. this.btnMusic = null;
  35181. this.icoMusic.destroy();
  35182. this.icoMusic = null;;
  35183. this.btnSound.destroy();
  35184. this.btnSound = null;;
  35185. this.icoSound.destroy();
  35186. this.icoSound = null;;
  35187. this.btnPlay.destroy();
  35188. this.btnPlay = null;
  35189. this.btnInfo.destroy();
  35190. this.btnInfo = null;
  35191. this.icoInfo.destroy();
  35192. this.icoInfo = null;
  35193. this.btnReset.destroy();
  35194. this.btnReset = null;
  35195. this.icoReset.destroy();
  35196. this.icoReset = null;
  35197. this.creditsGroup.destroy();
  35198. this.creditsGroup = null;
  35199. this.bgCredits.destroy();
  35200. this.bgCredits = null;
  35201. this.btnCreditsClose.destroy();
  35202. this.btnCreditsClose = null;
  35203. this.txtCreditsOk.destroy();
  35204. this.txtCreditsOk = null;
  35205. this.clearGroup.destroy();
  35206. this.clearGroup = null;
  35207. this.bgClear.destroy();
  35208. this.bgClear = null;
  35209. this.btnClearYes.destroy();
  35210. this.btnClearYes = null;
  35211. this.txtClearYes.destroy();
  35212. this.txtClearYes = null;
  35213. this.btnClearNo.destroy();
  35214. this.btnClearNo = null;
  35215. this.txtClearNo.destroy();
  35216. this.txtClearNo = null;
  35217. this.txtScore.destroy();
  35218. this.txtScore = null;
  35219. this.txtScoreValue.destroy();
  35220. this.txtScoreValue = null;
  35221. this.btnMoreGames.destroy();
  35222. this.btnMoreGames = null;
  35223. };
  35224. MenuState.prototype.resize = function () {
  35225. var scale = this.app.scale;
  35226. this.bg.scale.x = this.bg.scale.y = scale;
  35227. this.bg.y = this.app.fitSizes.height - 960 * scale;
  35228. this.mainLayer.scale.setTo(scale, scale);
  35229. this.mainLayer.x = (this.app.originSizes.width - this.windowWidth) / 2 * scale;
  35230. this.mainLayer.y = (this.app.fitSizes.height - this.windowHeight * scale) / 2;
  35231. this.creditsYOutScreen = -this.bgCredits.height - this.mainLayer.y - 150;
  35232. if (this.creditsGroup.visible === false)
  35233. this.creditsGroup.y = this.creditsYOutScreen;
  35234. this.clearYOutScreen = -this.bgClear.height - this.mainLayer.y - 150;
  35235. if (this.clearGroup.visible === false)
  35236. this.clearGroup.y = this.clearYOutScreen;
  35237. };
  35238. MenuState.prototype.onBtnPlayClick = function () {
  35239. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35240. if (this.creditsGroup.visible) return;
  35241. if (this.clearGroup.visible) return;
  35242. this.app.createPlayState();
  35243. this.destroy();
  35244. };
  35245. MenuState.prototype.onBtnInfoClick = function () {
  35246. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35247. if (this.creditsGroup.visible) return;
  35248. if (this.clearGroup.visible) return;
  35249. this.creditsGroup.visible = true;
  35250. TweenLite.to(this.creditsGroup, 1.0, { y: this.creditsYInScreen, ease: 'Expo.easeOut' } );
  35251. };
  35252. MenuState.prototype.onBtnResetClick = function () {
  35253. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35254. if (this.creditsGroup.visible) return;
  35255. if (this.clearGroup.visible) return;
  35256. this.clearGroup.visible = true;
  35257. TweenLite.to(this.clearGroup, 1.0, { y: this.clearYInScreen, ease: 'Expo.easeOut' } );
  35258. };
  35259. MenuState.prototype.onBtnMusicClick = function () {
  35260. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35261. var isMusic = !this.app.isMusic;
  35262. this.refreshBtns();
  35263. if (isMusic) this.app.unmute();
  35264. else this.app.mute();
  35265. };
  35266. MenuState.prototype.onBtnSoundClick = function () {
  35267. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35268. this.app.isSound = !this.app.isSound;
  35269. this.refreshBtns();
  35270. };
  35271. MenuState.prototype.refreshBtns = function () {
  35272. this.icoMusic.frameName = this.app.isMusic ? 'ico_music' : 'ico_music_off';
  35273. this.icoSound.frameName = this.app.isSound ? 'ico_sound' : 'ico_sound_off';
  35274. };
  35275. MenuState.prototype.onBtnCreditsCloseClick = function () {
  35276. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35277. TweenLite.to(this.creditsGroup, 0.6, { y: this.creditsYOutScreen, ease: 'Expo.easeOut', onCompleteScope: this, onComplete: function() {
  35278. this.creditsGroup.visible = false;
  35279. } } );
  35280. }
  35281. MenuState.prototype.onBtnClearYesClick = function () {
  35282. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35283. cookie.empty();
  35284. for (var i = 0; i < 30; i++) this.app.score[i] = 0;
  35285. this.app.levelMng.curr = 1;
  35286. this.txtScoreValue.setText(this.app.getTotalScore().toString());
  35287. TweenLite.to(this.clearGroup, 0.6, { y: this.clearYOutScreen, ease: 'Expo.easeOut', onCompleteScope: this, onComplete: function() {
  35288. this.clearGroup.visible = false;
  35289. } } );
  35290. };
  35291. MenuState.prototype.onBtnClearNoClick = function () {
  35292. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35293. TweenLite.to(this.clearGroup, 0.6, { y: this.clearYOutScreen, ease: 'Expo.easeOut', onCompleteScope: this, onComplete: function() {
  35294. this.clearGroup.visible = false;
  35295. } } );
  35296. };
  35297. /**
  35298. * User: qzix13
  35299. * Date: 12.12.13
  35300. */
  35301. function PlayState(app) {
  35302. app.playState = this;
  35303. this.app = app;
  35304. this.toolbarMaxHeight = 70;
  35305. this.cols = 5;
  35306. this.rows = 6;
  35307. this.cellSize = 100;
  35308. this.bulletSize = 25;
  35309. this.bulletDirections = ['left', 'right', 'up', 'down'];
  35310. this.bubbleSizes = [65, 75, 85, 95]; // from smaller to biggest (green, blue, yellow, red).
  35311. this.bubbleColors = ['green', 'blue', 'yellow', 'red'];
  35312. this.bubbleBlinkAnim = [
  35313. Phaser.Animation.generateFrameNames('bubble_green_', 1, 9, '', 4),
  35314. Phaser.Animation.generateFrameNames('bubble_blue_', 1, 9, '', 4),
  35315. Phaser.Animation.generateFrameNames('bubble_yellow_', 1, 9, '', 4),
  35316. Phaser.Animation.generateFrameNames('bubble_red_', 1, 9, '', 4)
  35317. ];
  35318. this.canvas = app.phaser.add.group(app.phaser.world, 'play_state_canvas');
  35319. this.bg = app.phaser.add.tileSprite(0, 0, 640, 960, 'bg');
  35320. this.canvas.add(this.bg);
  35321. this.gameLayer = app.phaser.add.group(this.canvas);
  35322. this.bulletsGroup = app.phaser.add.group(this.gameLayer);
  35323. this.bubblesGroup = app.phaser.add.group(this.gameLayer);
  35324. this.toolbarGroup = app.phaser.add.group(this.gameLayer);
  35325. this.pauseDlgGroup = app.phaser.add.group(this.canvas);
  35326. this.completeDlgGroup = app.phaser.add.group(this.canvas);
  35327. this.canvas.add(app.bgOver._container);
  35328. this.toolbar = new Toolbar(app);
  35329. this.pauseDlg = new PauseDlg(app);
  35330. this.pauseDlg.hide();
  35331. this.completeDlg = new CompleteDlg(app);
  35332. this._bullets = [];
  35333. this._bulletsCache = [];
  35334. this._bubbles = [];
  35335. this._requests = []; // { callback:function, callbackContext:Object, callbackArgs:Array }
  35336. this._addRequestsBlocked = false; // блокується в середині блоку обробки запитів.
  35337. this._isCheckCollide = true;
  35338. this._idleDelay = 0;
  35339. this._bulletsZeroDelay = 0;
  35340. this._leftClicks = 0;
  35341. this._levelClicks = 3;
  35342. this._score = 0;
  35343. this._countPoppedBubblesCombo = 0;
  35344. this._countPoppedBubbles = 0;
  35345. this._pause = false;
  35346. app.levelMng.create(app.levelMng.curr);
  35347. this.resize();
  35348. }
  35349. PlayState.prototype.destroy = function () {
  35350. var i = 0, n = 0;
  35351. this.app.playState = null;
  35352. this.app = null;
  35353. this.bulletDirections = null;
  35354. this.bubbleSizes = null;
  35355. this.bubbleColors = null;
  35356. this.bubbleBlinkAnim = null;
  35357. for (i = 0, n = this._bubbles.length; i < n; i++) {
  35358. this._bubbles[i].destroy();
  35359. }
  35360. for (i = 0, n = this._bullets.length; i < n; i++) {
  35361. this._bullets[i].destroy();
  35362. }
  35363. for (i = 0, n = this._bulletsCache.length; i < n; i++) {
  35364. this._bulletsCache[i].destroy();
  35365. }
  35366. this.canvas.destroy();
  35367. this.canvas = null;
  35368. this.gameLayer.destroy();
  35369. this.gameLayer = null;
  35370. this.bg.destroy();
  35371. this.bg = null;
  35372. this.bulletsGroup.destroy();
  35373. this.bulletsGroup = null;
  35374. this.bubblesGroup.destroy();
  35375. this.bubblesGroup = null;
  35376. this.toolbarGroup.destroy();
  35377. this.toolbarGroup = null;
  35378. this.pauseDlgGroup.destroy();
  35379. this.pauseDlgGroup = null;
  35380. this.toolbar.destroy();
  35381. this.toolbar = null;
  35382. this.pauseDlg.destroy();
  35383. this.pauseDlg = null;
  35384. this.completeDlg.destroy();
  35385. this.completeDlg = null;
  35386. this._bullets = null;
  35387. this._bulletsCache = null;
  35388. this._bubbles = null;
  35389. this._requests = null;
  35390. };
  35391. PlayState.prototype.resize = function () {
  35392. var scale = this.app.scale;
  35393. this.bg.scale.x = this.bg.scale.y = scale;
  35394. this.bg.y = this.app.fitSizes.height - 960 * scale;
  35395. this.gameLayer.scale.setTo(scale, scale);
  35396. this.gameLayer.x = (this.app.originSizes.width - this.cols * this.cellSize) / 2 * scale;
  35397. this.gameLayer.y = (this.app.fitSizes.height - (this.rows * this.cellSize * scale) - this.toolbarMaxHeight * scale) / 2;
  35398. this.pauseDlgGroup.scale.setTo(scale, scale);
  35399. //this.pauseDlgGroup.x = (this.app.originSizes.width - ) / 2 * scale;
  35400. this.pauseDlgGroup.y = (this.app.fitSizes.height - this.app.originSizes.height * scale) / 2;
  35401. this.completeDlgGroup.scale.setTo(scale, scale);
  35402. this.completeDlgGroup.x = (this.app.fitSizes.width - 400 * scale) / 2;
  35403. this.completeDlgGroup.y = (this.app.fitSizes.height - 250 * scale) / 2.2;
  35404. };
  35405. PlayState.prototype.update = function () {
  35406. if (this._pause) return;
  35407. var i = 0, j = 0, n = 0, m = 0;
  35408. if (this._isCheckCollide && this._bullets.length > 0) {
  35409. var bullet, bubble;
  35410. for (i = 0, n = this._bullets.length; i < n; i++) {
  35411. bullet = this._bullets[i].sprite;
  35412. for (j = 0, m = this._bubbles.length; j < m; j++) {
  35413. bubble = this._bubbles[j].sprite;
  35414. if (this.distance(bullet.x, bullet.y, bubble.x, bubble.y) < this.bulletSize) {
  35415. bullet.self.pause();
  35416. bubble.self.grow(bullet.self);
  35417. }
  35418. }
  35419. }
  35420. this._bulletsZeroDelay = 0;
  35421. } else {
  35422. this.writeComboScore();
  35423. this._bulletsZeroDelay++;
  35424. if (this._bulletsZeroDelay > 20 && this._leftClicks <= 0) this.completeDlg.show('txt_level_failed', this._score);
  35425. }
  35426. this._idleDelay++;
  35427. if (this._idleDelay > 300 / this._bubbles.length) {
  35428. n = this.app.phaser.rnd.integerInRange(1, 3);
  35429. for (i = 0; i < n; i++) {
  35430. var numBubble = this.app.phaser.rnd.integerInRange(0, this._bubbles.length);
  35431. this._bubbles[numBubble].makeBlinking();
  35432. }
  35433. this._idleDelay = 0;
  35434. }
  35435. // Перевіряємо чи вилетіли кулі за екран.
  35436. var n = this._bullets.length;
  35437. var i = 0;
  35438. var gameWidth = this.app.originSizes.width;
  35439. var gameHeight = this.app.originSizes.height;
  35440. for (i = 0; i < n; i++) {
  35441. var bullet = this._bullets[i];
  35442. var bulletSpr = bullet.sprite;
  35443. var x = bulletSpr.x;
  35444. var y = bulletSpr.y + this.gameLayer.y;
  35445. var size = bulletSpr.width + 50;
  35446. if (x < -size || x > gameWidth + size
  35447. || y < -size || y > gameHeight) {
  35448. bullet.stop();
  35449. }
  35450. if (bullet.direction == 'left' || bullet.direction == 'right') bulletSpr.y = bullet.initY;
  35451. else if (bullet.direction == 'up' || bullet.direction == 'down') bulletSpr.x = bullet.initX;
  35452. }
  35453. // requests
  35454. if (this._requests.length > 0) {
  35455. this._addRequestsBlocked = true;
  35456. var n = this._requests.length;
  35457. for (i = 0; i < n; i++) {
  35458. if (this._requests[i] == null) continue;
  35459. var callback = this._requests[i].callback;
  35460. var callbackContext = this._requests[i].callbackContext;
  35461. var callbackArgs = this._requests[i].callbackArgs;
  35462. callback.call(callbackContext, callbackArgs);
  35463. }
  35464. this._requests.splice(0, n);
  35465. this._addRequestsBlocked = false;
  35466. }
  35467. };
  35468. PlayState.prototype.addBubble = function (bubble) {
  35469. var index = this._bubbles.indexOf(bubble, 0);
  35470. if (index < 0) this._bubbles[this._bubbles.length] = bubble;
  35471. };
  35472. PlayState.prototype.addBullet = function (bullet) {
  35473. var index = this._bullets.indexOf(bullet, 0);
  35474. if (index < 0) this._bullets[this._bullets.length] = bullet;
  35475. index = this._bulletsCache.indexOf(bullet, 0);
  35476. if (index >= 0) this._bulletsCache.splice(index, 1);
  35477. };
  35478. PlayState.prototype.addBulletInCache = function (bubble) {
  35479. var index = this._bulletsCache.indexOf(bubble, 0);
  35480. if (index < 0) this._bulletsCache[this._bulletsCache.length] = bubble;
  35481. index = this._bullets.indexOf(bubble, 0);
  35482. if (index >= 0) this._bullets.splice(index, 1);
  35483. };
  35484. PlayState.prototype.addRequest = function (callback, callbackContext, callbackArgs) {
  35485. if (this._addRequestsBlocked) throw 'Adding requests blocked.'
  35486. callbackContext = callbackContext || null;
  35487. callbackArgs = callbackArgs || null;
  35488. if (callback == null) return;
  35489. this._requests[this._requests.length] = {
  35490. callback: callback,
  35491. callbackContext: callbackContext,
  35492. callbackArgs: callbackArgs
  35493. };
  35494. };
  35495. PlayState.prototype.getBullet = function () {
  35496. var bullet = this._bulletsCache.pop();
  35497. if (bullet == null) bullet = new Bullet(this.app);
  35498. return bullet;
  35499. };
  35500. PlayState.prototype.pause = function (isPause) {
  35501. this._pause = isPause;
  35502. var i = 0, n = 0;
  35503. if (this._bullets) {
  35504. n = this._bullets.length;
  35505. for (i = 0; i < n; i++) {
  35506. if (isPause) this._bullets[i].pause();
  35507. else this._bullets[i].continue();
  35508. }
  35509. }
  35510. };
  35511. PlayState.prototype.reset = function () {
  35512. this._isCheckCollide = false;
  35513. var i = 0;
  35514. var n = this._bullets.length;
  35515. for (i = 0; i < n; i++) this._bullets[i].stop();
  35516. n = this._bubbles.length;
  35517. for (i = 0; i < n; i++) this._bubbles[i].reset();
  35518. this.resetLevelData(this.app.levelMng.curr, this._levelClicks);
  35519. this._requests.splice(0, n);
  35520. this._addRequestsBlocked = false;
  35521. this._isCheckCollide = true;
  35522. };
  35523. PlayState.prototype.resetLevelData = function (level, clicks) {
  35524. this.toolbar.setScore(this._score = 0);
  35525. this.toolbar.setClicks(this._leftClicks = this._levelClicks = clicks);
  35526. this.toolbar.setLevel(level);
  35527. this.toolbar.hideCombo();
  35528. this._countPoppedBubblesCombo = 0;
  35529. this._countPoppedBubbles = 0;
  35530. };
  35531. PlayState.prototype.addOnePoppedBubble = function () {
  35532. if (++this._countPoppedBubblesCombo >= 4) {
  35533. this.toolbar.setCombo(this.getComboScore());
  35534. }
  35535. this.toolbar.setScore(this._score += 75);
  35536. this._countPoppedBubbles++;
  35537. if (this._countPoppedBubbles >= this._bubbles.length) {
  35538. this.writeComboScore();
  35539. if (this.app.levelMng.curr >= this.app.levelMng.total) {
  35540. this.completeDlg.show('txt_congratulations', this._score);
  35541. } else {
  35542. this.completeDlg.show('txt_level_complete', this._score);
  35543. }
  35544. }
  35545. };
  35546. PlayState.prototype.subOneClick = function () {
  35547. this._bulletsZeroDelay = 0;
  35548. this.writeComboScore();
  35549. var canClick = this._leftClicks-- > 0;
  35550. if (this._leftClicks < 0) this._leftClicks = 0;
  35551. this.toolbar.setClicks(this._leftClicks);
  35552. return canClick;
  35553. };
  35554. PlayState.prototype.writeComboScore = function () {
  35555. if (this._countPoppedBubblesCombo == 0) return;
  35556. // Додати бали за комбо.
  35557. if (this._countPoppedBubblesCombo >= 4) {
  35558. this.toolbar.setScore(this._score += this.getComboScore());
  35559. }
  35560. this._countPoppedBubblesCombo = 0;
  35561. this.toolbar.hideCombo();
  35562. };
  35563. PlayState.prototype.getComboScore = function () {
  35564. return this._countPoppedBubblesCombo * (5 + this._countPoppedBubblesCombo * 5);
  35565. };
  35566. PlayState.prototype.distance = function (x1, y1, x2, y2) {
  35567. var dX = x1 - x2;
  35568. var dY = y1 - y2;
  35569. return Math.sqrt(dX * dX + dY * dY);
  35570. };
  35571. /**
  35572. * User: qzix13
  35573. * Date: 27.12.13
  35574. */
  35575. function PauseDlg(app) {
  35576. this.app = app;
  35577. /*this.bg = app.phaser.add.graphics(0, 0);
  35578. this.bg.beginFill(0x0, 0.4);
  35579. this.bg.drawRect(0, 0, 640, 960);
  35580. this.bg.endFill();
  35581. app.playState.pauseDlgGroup.add(this.bg);*/
  35582. this.bg = app.phaser.add.child(app.playState.pauseDlgGroup, 0, 0, 'bg_pause');
  35583. this.bg.inputEnabled = true;
  35584. this.txtPause = app.phaser.add.child(app.playState.pauseDlgGroup, app.originSizes.width / 2, app.originSizes.height / 3.4, 'txt_atlas');
  35585. this.txtPause.frameName = 'txt_pause';
  35586. this.txtPause.anchor.setTo(.5,.5);
  35587. this.txtPause.scale.setTo(.8,.8);
  35588. var center = app.originSizes.width / 2;
  35589. var scale = 0.85;
  35590. var btnsOffset = 100;
  35591. var btns1Y = app.originSizes.height / 2.4;
  35592. var btns2Y = btns1Y + btnsOffset;
  35593. var btns3Y = btns2Y + btnsOffset;
  35594. var btns4Y = btns3Y + btnsOffset;
  35595. var txtScale = 0.7;
  35596. this.btnMenu = app.phaser.add.button(center - btnsOffset, btns1Y, 'game_atlas', this.onBtnMenuClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35597. this.btnMenu.scale.setTo(scale, scale);
  35598. this.btnMenu.anchor.setTo(.5, .5);
  35599. app.playState.pauseDlgGroup.add(this.btnMenu);
  35600. this.icoMenu = app.phaser.add.child(app.playState.pauseDlgGroup, this.btnMenu.x, this.btnMenu.y, 'game_atlas');
  35601. this.icoMenu.frameName = 'ico_menu';
  35602. this.icoMenu.anchor.setTo(.5, .5);
  35603. this.icoMenu.scale.copyFrom(this.btnMenu.scale);
  35604. this.icoMenu.scale.subtract(0.2, 0.2);
  35605. this.btnReset = app.phaser.add.button(center, btns1Y, 'game_atlas', this.onBtnResetClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35606. this.btnReset.scale.setTo(scale, scale);
  35607. this.btnReset.anchor.setTo(.5, .5);
  35608. app.playState.pauseDlgGroup.add(this.btnReset);
  35609. this.icoReset = app.phaser.add.child(app.playState.pauseDlgGroup, this.btnReset.x, this.btnReset.y, 'game_atlas');
  35610. this.icoReset.frameName = 'ico_reset';
  35611. this.icoReset.anchor.setTo(.5, .5);
  35612. this.icoReset.scale.copyFrom(this.btnReset.scale);
  35613. this.icoReset.scale.subtract(0.2, 0.2);
  35614. this.btnPlay = app.phaser.add.button(center + btnsOffset, btns1Y, 'game_atlas', this.onBtnPlayClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35615. this.btnPlay.scale.setTo(scale, scale);
  35616. this.btnPlay.anchor.setTo(.5, .5);
  35617. app.playState.pauseDlgGroup.add(this.btnPlay);
  35618. this.icoPlay = app.phaser.add.child(app.playState.pauseDlgGroup, this.btnPlay.x, this.btnPlay.y, 'game_atlas');
  35619. this.icoPlay.frameName = 'ico_play';
  35620. this.icoPlay.anchor.setTo(.5, .5);
  35621. this.icoPlay.scale.copyFrom(this.btnPlay.scale);
  35622. this.icoPlay.scale.subtract(0.2, 0.2);
  35623. this.btnMusic = app.phaser.add.button(center - btnsOffset / 2, btns2Y, 'game_atlas', this.onBtnMusicClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35624. this.btnMusic.scale.setTo(scale, scale);
  35625. this.btnMusic.anchor.setTo(.5, .5);
  35626. app.playState.pauseDlgGroup.add(this.btnMusic);
  35627. this.icoMusic = app.phaser.add.child(app.playState.pauseDlgGroup, this.btnMusic.x, this.btnMusic.y, 'game_atlas');
  35628. this.icoMusic.frameName = this.app.isMusic ? 'ico_music' : 'ico_music_off';
  35629. this.icoMusic.anchor.setTo(.5, .5);
  35630. this.icoMusic.scale.copyFrom(this.btnMusic.scale);
  35631. this.icoMusic.scale.subtract(0.2, 0.2);
  35632. this.btnSound = app.phaser.add.button(center + btnsOffset / 2, btns2Y, 'game_atlas', this.onBtnSoundClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35633. this.btnSound.scale.setTo(scale, scale);
  35634. this.btnSound.anchor.setTo(.5, .5);
  35635. app.playState.pauseDlgGroup.add(this.btnSound);
  35636. this.icoSound = app.phaser.add.child(app.playState.pauseDlgGroup, this.btnSound.x, this.btnSound.y, 'game_atlas');
  35637. this.icoSound.frameName = this.app.isSound ? 'ico_sound' : 'ico_sound_off';
  35638. this.icoSound.anchor.setTo(.5, .5);
  35639. this.icoSound.scale.copyFrom(this.btnSound.scale);
  35640. this.icoSound.scale.subtract(0.2, 0.2);
  35641. /*this.btnWalkthrough = app.phaser.add.button(center + btnsOffset, btns2Y, 'game_atlas', this.onBtnWalkthroughClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35642. this.btnWalkthrough.scale.setTo(scale, scale);
  35643. this.btnWalkthrough.anchor.setTo(.5, .5);
  35644. app.playState.pauseDlgGroup.add(this.btnWalkthrough);
  35645. this.icoWalkthrough = app.phaser.add.child(app.playState.pauseDlgGroup, this.btnWalkthrough.x, this.btnWalkthrough.y, 'game_atlas');
  35646. this.icoWalkthrough.frameName = 'ico_walkthrough';
  35647. this.icoWalkthrough.anchor.setTo(.5, .5);
  35648. this.icoWalkthrough.scale.copyFrom(this.btnWalkthrough.scale);*/
  35649. /*this.btnMoreGames = app.phaser.add.button(center, btns3Y, 'button_more_games', app.gotoSponsor, this, 2, 1, 0);
  35650. this.btnMoreGames.scale.setTo(scale, scale);
  35651. this.btnMoreGames.anchor.setTo(.5, .5);
  35652. app.playState.pauseDlgGroup.add(this.btnMoreGames);
  35653. this.spilLogo = app.phaser.add.child(app.playState.pauseDlgGroup, center, btns4Y, 'spil_atlas');
  35654. this.spilLogo.frameName = 'mascot_1';
  35655. this.spilLogo.anchor.setTo(.5, .5);
  35656. this.spilLogo.scale.setTo(.8, .8);
  35657. this.spilLogo.inputEnabled = true;
  35658. this.spilLogo.events.onInputDown.add(function() { app.gotoSponsor(); });*/
  35659. }
  35660. PauseDlg.prototype.destroy = function () {
  35661. this.app = null;
  35662. this.bg.destroy();
  35663. this.bg = null;
  35664. this.txtPause.destroy();
  35665. this.txtPause = null;
  35666. this.btnMenu.destroy();
  35667. this.btnMenu = null;
  35668. this.icoMenu.destroy();
  35669. this.icoMenu = null;
  35670. this.btnReset.destroy();
  35671. this.btnReset = null;
  35672. this.icoReset.destroy();
  35673. this.icoReset = null;
  35674. this.btnPlay.destroy();
  35675. this.btnPlay = null;
  35676. this.icoPlay.destroy();
  35677. this.icoPlay = null;
  35678. this.btnMusic.destroy();
  35679. this.btnMusic = null;
  35680. this.icoMusic.destroy();
  35681. this.icoMusic = null;
  35682. this.btnSound.destroy();
  35683. this.btnSound = null;
  35684. this.icoSound.destroy();
  35685. this.icoSound = null;
  35686. /*this.btnWalkthrough.destroy();
  35687. this.btnWalkthrough = null;
  35688. this.icoWalkthrough.destroy();
  35689. this.icoWalkthrough = null;*/
  35690. /*this.btnMoreGames.destroy();
  35691. this.btnMoreGames = null;
  35692. this.spilLogo.destroy();
  35693. this.spilLogo = null;*/
  35694. };
  35695. PauseDlg.prototype.show = function () {
  35696. this.app.playState.pauseDlgGroup.visible = true;
  35697. this.app.playState.pause(true);
  35698. };
  35699. PauseDlg.prototype.hide = function () {
  35700. this.app.playState.pauseDlgGroup.visible = false;
  35701. this.app.playState.pause(false);
  35702. };
  35703. PauseDlg.prototype.onBtnMenuClick = function () {
  35704. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35705. if (this.app.isMusic && !this.app.mainThemeSound.isPlaying) this.app.mainThemeSound.play('', 0, 1, true, true);
  35706. this.app.createMenuState();
  35707. this.app.playState.destroy();
  35708. };
  35709. PauseDlg.prototype.onBtnResetClick = function () {
  35710. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35711. this.hide();
  35712. this.app.playState.reset();
  35713. if (this.app.isMusic && !this.app.mainThemeSound.isPlaying) this.app.mainThemeSound.play('', 0, 1, true, true);
  35714. };
  35715. PauseDlg.prototype.onBtnPlayClick = function () {
  35716. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35717. this.hide();
  35718. if (this.app.isMusic && !this.app.mainThemeSound.isPlaying) this.app.mainThemeSound.play('', 0, 1, true, true);
  35719. };
  35720. PauseDlg.prototype.onBtnMusicClick = function () {
  35721. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35722. if (this.app.isMusic && !this.app.mainThemeSound.isPlaying) this.app.mainThemeSound.play('', 0, 1, true, true);
  35723. var isMusic = !this.app.isMusic;
  35724. this.refreshBtns();
  35725. if (isMusic) this.app.unmute();
  35726. else this.app.mute();
  35727. };
  35728. PauseDlg.prototype.onBtnSoundClick = function () {
  35729. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35730. this.app.isSound = !this.app.isSound;
  35731. this.refreshBtns();
  35732. if (this.app.isMusic && !this.app.mainThemeSound.isPlaying) this.app.mainThemeSound.play('', 0, 1, true, true);
  35733. };
  35734. PauseDlg.prototype.onBtnWalkthroughClick = function () {
  35735. window.open('https://www.youtube.com/watch?v=VJVGHiQCOsQ', '_blank');
  35736. };
  35737. PauseDlg.prototype.refreshBtns = function () {
  35738. this.icoMusic.frameName = this.app.isMusic ? 'ico_music' : 'ico_music_off';
  35739. this.icoSound.frameName = this.app.isSound ? 'ico_sound' : 'ico_sound_off';
  35740. };
  35741. /**
  35742. * User: qzix13
  35743. * Date: 28.12.13
  35744. */
  35745. function CompleteDlg(app) {
  35746. this.app = app;
  35747. this.showed = false;
  35748. var txtScale = 0.8;
  35749. var cellSize = app.playState.cellSize;
  35750. var halfCellSize = cellSize / 2;
  35751. var center = 430 / 2;
  35752. var scale = 0.75;//0.58;
  35753. var btnsOffset = 100;//63;
  35754. var btns1Y = 200;
  35755. var btns2Y = 200;//btns1Y - 60;
  35756. this.isBusy = false;
  35757. this.group = app.phaser.add.group(app.playState.completeDlgGroup);
  35758. this.bg = app.phaser.add.child(this.group, 0, 0, 'bg_complete');
  35759. this.bg.inputEnabled = true;
  35760. this.txtCaption = app.phaser.add.child(this.group, 190, 40, 'txt_atlas');
  35761. this.txtCaption.frameName = 'txt_level_complete';
  35762. this.txtCaption.anchor.setTo(.5, .5);
  35763. this.txtCaption.scale.setTo(txtScale, txtScale);
  35764. this.txtScore = app.phaser.add.child(this.group, 75, 105, 'txt_atlas');
  35765. this.txtScore.frameName = 'txt_score';
  35766. this.txtScore.anchor.setTo(.5,.5);
  35767. this.txtScore.scale.setTo(txtScale, txtScale);
  35768. this.txtScoreValue = app.phaser.add.bitmapText(this.txtScore.x + this.txtScore.width / 1.8 - 4, this.txtScore.y + 1.5, '99999999', { font: '26px HoboDigits', align: 'left' });
  35769. this.txtScoreValue.anchor.setTo(.0, .5);
  35770. this.group.add(this.txtScoreValue);
  35771. /*this.btnMoreGames = app.phaser.add.button(115, btns1Y, 'button_more_games', app.gotoSponsor, this, 2, 1, 0);
  35772. this.btnMoreGames.scale.setTo(scale, scale);
  35773. this.btnMoreGames.anchor.setTo(.5, .5);
  35774. this.group.add(this.btnMoreGames);*/
  35775. /*this.spilLogo = app.phaser.add.child(this.group, center, btns1Y - 65, 'spil_atlas');
  35776. this.spilLogo.frameName = 'mascot_1';
  35777. this.spilLogo.anchor.setTo(.5, .5);
  35778. this.spilLogo.scale.setTo(.6, .6);
  35779. this.spilLogo.inputEnabled = true;
  35780. this.spilLogo.events.onInputDown.add(function() { app.gotoSponsor(); });*/
  35781. this.btnReset = app.phaser.add.button(center, btns2Y, 'game_atlas', this.onBtnResetClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35782. this.btnReset.scale.setTo(scale, scale);
  35783. this.btnReset.anchor.setTo(.5, .5);
  35784. this.group.add(this.btnReset);
  35785. this.icoReset = app.phaser.add.child(this.group, this.btnReset.x, this.btnReset.y, 'game_atlas');
  35786. this.icoReset.frameName = 'ico_reset';
  35787. this.icoReset.anchor.setTo(.5, .5);
  35788. this.icoReset.scale.copyFrom(this.btnReset.scale);
  35789. this.icoReset.scale.subtract(0.2, 0.2);
  35790. this.btnMenu = app.phaser.add.button(center - btnsOffset, btns2Y, 'game_atlas', this.onBtnMenuClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35791. this.btnMenu.scale.setTo(scale, scale);
  35792. this.btnMenu.anchor.setTo(.5, .5);
  35793. this.group.add(this.btnMenu);
  35794. this.icoMenu = app.phaser.add.child(this.group, this.btnMenu.x, this.btnMenu.y, 'game_atlas');
  35795. this.icoMenu.frameName = 'ico_menu';
  35796. this.icoMenu.anchor.setTo(.5, .5);
  35797. this.icoMenu.scale.copyFrom(this.btnMenu.scale);
  35798. this.icoMenu.scale.subtract(0.2, 0.2);
  35799. this.btnNext = app.phaser.add.button(center + btnsOffset, btns2Y, 'game_atlas', this.onBtnNextClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35800. this.btnNext.scale.setTo(scale, scale);
  35801. this.btnNext.anchor.setTo(.5, .5);
  35802. this.group.add(this.btnNext);
  35803. this.icoNext = app.phaser.add.child(this.group, this.btnNext.x, this.btnNext.y, 'game_atlas');
  35804. this.icoNext.frameName = 'ico_next';
  35805. this.icoNext.anchor.setTo(.5, .5);
  35806. this.icoNext.scale.copyFrom(this.btnNext.scale);
  35807. this.icoNext.scale.subtract(0.2, 0.2);
  35808. this.app.playState.completeDlgGroup.visible = false;
  35809. this.group.visible = false;
  35810. this.group.y = -app.fitSizes.height;
  35811. }
  35812. CompleteDlg.prototype.destroy = function () {
  35813. this.app = null;
  35814. this.group.destroy();
  35815. this.group = null;
  35816. this.bg.destroy();
  35817. this.bg = null;
  35818. this.txtScore.destroy();
  35819. this.txtScore = null;
  35820. this.txtScoreValue.destroy();
  35821. this.txtScoreValue = null;
  35822. this.btnReset.destroy();
  35823. this.btnReset = null;
  35824. this.icoReset.destroy();
  35825. this.icoReset = null;
  35826. this.btnMenu.destroy();
  35827. this.btnMenu = null;
  35828. this.icoMenu.destroy();
  35829. this.icoMenu = null;
  35830. this.btnNext.destroy();
  35831. this.btnNext = null;
  35832. this.icoNext.destroy();
  35833. this.icoNext = null;
  35834. /*this.btnMoreGames.destroy();
  35835. this.btnMoreGames = null;
  35836. this.spilLogo.destroy();
  35837. this.spilLogo = null;*/
  35838. };
  35839. CompleteDlg.prototype.show = function (caption, score) {
  35840. if (this.showed) return;
  35841. this.isBusy = true;
  35842. this.showed = true;
  35843. caption = caption || 'txt_level_complete';
  35844. score = score || 0;
  35845. this.txtCaption.frameName = caption;
  35846. this.txtScoreValue.setText(score.toString());
  35847. this.app.playState.completeDlgGroup.visible = this.group.visible = true;
  35848. this.btnNext.visible = this.icoNext.visible = caption === 'txt_level_complete';
  35849. if (this.app.isCanPlayAudio && this.app.isSound) {
  35850. if (caption != 'txt_level_failed') this.app.levelCompleteSound.play();
  35851. else this.app.levelFailedSound.play();
  35852. }
  35853. this.app.saveScore(this.app.levelMng.curr, score);
  35854. TweenLite.to(this.group, 1.0, { y: 0.0, ease: 'Expo.easeOut' } );
  35855. TweenLite.to(this.app.playState.toolbarGroup, 1.0, { alpha: 0.0, onCompleteScope: this, onComplete: function() { this.isBusy = false; this.app.playState.toolbarGroup.visible = false; } } );
  35856. if (caption === 'txt_level_complete') {
  35857. SG_Hooks.levelUp(parseInt(this.app.levelMng.curr), parseInt(score));
  35858. } else if (caption === 'txt_level_failed') {
  35859. SG_Hooks.gameOver(parseInt(this.app.levelMng.curr), parseInt(this.app.getTotalScore()));
  35860. }
  35861. };
  35862. CompleteDlg.prototype.hide = function (onComplete, onCompleteScope) {
  35863. if (this.showed === false) return;
  35864. this.isBusy = true;
  35865. this.app.playState.toolbarGroup.visible = true;
  35866. TweenLite.to(this.group, 0.5, { y: -this.app.fitSizes.height - 100, onCompleteScope: this, onComplete: function()
  35867. { this.app.playState.completeDlgGroup.visible = this.group.visible = false; this.showed = false; this.isBusy = false; } } );
  35868. TweenLite.to(this.app.playState.toolbarGroup, 0.5, { alpha: 1.0, onComplete: onComplete, onCompleteScope: onCompleteScope } );
  35869. };
  35870. CompleteDlg.prototype.hide2 = function () {
  35871. this.app.playState.toolbarGroup.visible = true;
  35872. this.app.playState.toolbarGroup.alpha = 1.0;
  35873. if (this.showed === false) return;
  35874. this.group.y = -this.app.fitSizes.height,
  35875. this.app.playState.completeDlgGroup.visible = this.group.visible = false;
  35876. this.isBusy = false;
  35877. this.showed = false;
  35878. };
  35879. CompleteDlg.prototype.onBtnMenuClick = function () {
  35880. if (this.isBusy) return;
  35881. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35882. if (this.app.isMusic && !this.app.mainThemeSound.isPlaying) this.app.mainThemeSound.play('', 0, 1, true, true);
  35883. if (this.app.levelMng.curr >= this.app.levelMng.total) {
  35884. this.app.levelMng.curr = 1;
  35885. cookie.set('lc', '1');
  35886. }
  35887. TweenLite.killTweensOf(this.group);
  35888. TweenLite.killTweensOf(this.app.playState.toolbarGroup);
  35889. this.app.createMenuState();
  35890. this.app.playState.destroy();
  35891. };
  35892. CompleteDlg.prototype.onBtnResetClick = function () {
  35893. if (this.isBusy) return;
  35894. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35895. if (this.app.isMusic && !this.app.mainThemeSound.isPlaying) this.app.mainThemeSound.play('', 0, 1, true, true);
  35896. this.app.playState.reset();
  35897. this.hide();
  35898. };
  35899. CompleteDlg.prototype.onBtnNextClick = function () {
  35900. if (this.isBusy) return;
  35901. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  35902. if (this.app.isMusic && !this.app.mainThemeSound.isPlaying) this.app.mainThemeSound.play('', 0, 1, true, true);
  35903. TweenLite.to(this.app.playState.canvas, 0.15, { alpha: 0.0, onCompleteScope: this, onComplete: function() {
  35904. this.app.playState.canvas.visible = true;
  35905. this.app.levelMng.next();
  35906. this.hide2();
  35907. } } );
  35908. TweenLite.to(this.app.playState.canvas, 0.15, { alpha: 1.0, delay: 0.3 } );
  35909. //this.app.playState.canvas.visible = false;
  35910. /*TweenLite.delayedCall(0.1, function() {
  35911. this.app.playState.canvas.visible = true;
  35912. this.app.levelMng.next();
  35913. this.hide2();
  35914. }, null, this);*/
  35915. };
  35916. /**
  35917. * User: qzix13
  35918. * Date: 23.12.13
  35919. */
  35920. function Toolbar(app) {
  35921. this.app = app;
  35922. var cellSize = app.playState.cellSize;
  35923. var rows = app.playState.rows;
  35924. var btnsY = cellSize * rows + cellSize / 2.5;
  35925. var txt1Y = cellSize * rows + cellSize * 0.2;
  35926. var txt2Y = cellSize * rows + cellSize * 0.58;
  35927. var txtScale = 0.7;
  35928. /*var width = cellSize * 5;
  35929. cellSize = width / 6;*/
  35930. var halfCellSize = cellSize / 2;
  35931. this.btnPause = app.phaser.add.button(halfCellSize, btnsY, 'game_atlas', this.onBtnPauseClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35932. this.btnPause.width = this.btnPause.height = app.playState.toolbarMaxHeight;
  35933. this.btnPause.anchor.setTo(.5, .5);
  35934. app.playState.toolbarGroup.add(this.btnPause);
  35935. this.icoPause = app.phaser.add.child(app.playState.toolbarGroup, this.btnPause.x, this.btnPause.y, 'game_atlas');
  35936. this.icoPause.frameName = 'ico_pause';
  35937. this.icoPause.anchor.setTo(.5, .5);
  35938. this.icoPause.scale.copyFrom(this.btnPause.scale);
  35939. this.icoPause.scale.subtract(0.2, 0.2);
  35940. this.btnReset = app.phaser.add.button(cellSize + halfCellSize, btnsY, 'game_atlas', this.onBtnResetClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35941. this.btnReset.width = this.btnReset.height = app.playState.toolbarMaxHeight;
  35942. this.btnReset.anchor.setTo(.5, .5);
  35943. app.playState.toolbarGroup.add(this.btnReset);
  35944. this.icoReset = app.phaser.add.child(app.playState.toolbarGroup, this.btnReset.x, this.btnReset.y, 'game_atlas');
  35945. this.icoReset.frameName = 'ico_reset';
  35946. this.icoReset.anchor.setTo(.5, .5);
  35947. this.icoReset.scale.copyFrom(this.btnReset.scale);
  35948. this.icoReset.scale.subtract(0.2, 0.2);
  35949. /*this.btnWalkthrough = app.phaser.add.button(cellSize *2 + halfCellSize, btnsY, 'game_atlas', this.onBtnWalkthroughClick, this, 'button_100_over', 'button_100_up', 'button_100_down');
  35950. this.btnWalkthrough.width = this.btnWalkthrough.height = app.playState.toolbarMaxHeight;
  35951. this.btnWalkthrough.anchor.setTo(.5, .5);
  35952. app.playState.toolbarGroup.add(this.btnWalkthrough);
  35953. this.icoWalkthrough = app.phaser.add.child(app.playState.toolbarGroup, this.btnWalkthrough.x, this.btnWalkthrough.y, 'game_atlas');
  35954. this.icoWalkthrough.frameName = 'ico_walkthrough';
  35955. this.icoWalkthrough.anchor.setTo(.5, .5);
  35956. this.icoWalkthrough.scale.copyFrom(this.btnWalkthrough.scale);*/
  35957. this.txtScore = app.phaser.add.child(app.playState.toolbarGroup, cellSize * 2 + halfCellSize, txt1Y, 'txt_atlas');
  35958. this.txtScore.frameName = 'txt_score';
  35959. this.txtScore.anchor.setTo(.5,.5);
  35960. this.txtScore.scale.setTo(txtScale, txtScale);
  35961. this.txtScoreValue = app.phaser.add.bitmapText(this.txtScore.x, txt2Y, '999', { font: '28px HoboDigits', align: 'center' });
  35962. this.txtScoreValue.anchor.setTo(.5, .5);
  35963. app.playState.toolbarGroup.add(this.txtScoreValue);
  35964. this.txtClicks = app.phaser.add.child(app.playState.toolbarGroup, cellSize * 3 + halfCellSize, txt1Y, 'txt_atlas');
  35965. this.txtClicks.frameName = 'txt_clicks';
  35966. this.txtClicks.anchor.setTo(.5,.5);
  35967. this.txtClicks.scale.setTo(txtScale, txtScale);
  35968. this.txtClicksValue = app.phaser.add.bitmapText(this.txtClicks.x, txt2Y, '2', { font: '28px HoboDigits', align: 'center' });
  35969. this.txtClicksValue.anchor.setTo(.5, .5);
  35970. app.playState.toolbarGroup.add(this.txtClicksValue);
  35971. this.txtLevel = app.phaser.add.child(app.playState.toolbarGroup, cellSize * 4 + halfCellSize, txt1Y, 'txt_atlas');
  35972. this.txtLevel.frameName = 'txt_level';
  35973. this.txtLevel.anchor.setTo(.5,.5);
  35974. this.txtLevel.scale.setTo(txtScale, txtScale);
  35975. this.txtLevelValue = app.phaser.add.bitmapText(this.txtLevel.x, txt2Y, '30', { font: '28px HoboDigits', align: 'center' });
  35976. this.txtLevelValue.anchor.setTo(.5, .5);
  35977. app.playState.toolbarGroup.add(this.txtLevelValue);
  35978. /*this.spilLogo = app.phaser.add.child(app.playState.toolbarGroup, cellSize * 5 + halfCellSize, btnsY, 'spil_atlas');
  35979. this.spilLogo.frameName = 'logo_m';
  35980. this.spilLogo.anchor.setTo(.5, .5);
  35981. this.spilLogo.scale.setTo(.5, .5);
  35982. this.spilLogo.inputEnabled = true;
  35983. this.spilLogo.events.onInputDown.add(function() { app.gotoSponsor(); });*/
  35984. this.txtCombo = app.phaser.add.child(app.playState.toolbarGroup, halfCellSize - 10, 10, 'txt_atlas');
  35985. this.txtCombo.frameName = 'txt_combo';
  35986. this.txtCombo.anchor.setTo(.5,.5);
  35987. this.txtCombo.scale.setTo(txtScale, txtScale);
  35988. this.txtComboValue = app.phaser.add.bitmapText(cellSize / 1.2 + 2, this.txtCombo.y + 1.5, '+315', { font: '26px HoboDigits', align: 'left' });
  35989. this.txtComboValue.anchor.setTo(.0, .5);
  35990. app.playState.toolbarGroup.add(this.txtComboValue);
  35991. this.hideCombo();
  35992. var currScaleX = this.txtClicksValue.scale.x;
  35993. var currScaleY = this.txtClicksValue.scale.y;
  35994. this.tlClicksValue = new TimelineLite();
  35995. this.tlClicksValue.to(this.txtClicksValue.scale, 0.1, { x: currScaleX + .3, y: currScaleY - .3 } );
  35996. this.tlClicksValue.to(this.txtClicksValue.scale, 0.1, { x: currScaleX - .3, y: currScaleY + .3 } );
  35997. this.tlClicksValue.to(this.txtClicksValue.scale, 0.1, { x: currScaleX + .2, y: currScaleY - .2 } );
  35998. this.tlClicksValue.to(this.txtClicksValue.scale, 0.1, { x: currScaleX - .2, y: currScaleY + .2 } );
  35999. this.tlClicksValue.to(this.txtClicksValue.scale, 0.1, { x: currScaleX + .1, y: currScaleY - .1 } );
  36000. this.tlClicksValue.to(this.txtClicksValue.scale, 0.1, { x: currScaleX - .1, y: currScaleY + .1 } );
  36001. this.tlClicksValue.to(this.txtClicksValue.scale, 0.1, { x: currScaleX, y: currScaleY } );
  36002. this.tlClicksValue.gotoAndStop(0.0);
  36003. }
  36004. Toolbar.prototype.destroy = function () {
  36005. this.app = null;
  36006. this.btnPause.destroy();
  36007. this.btnPause = null;
  36008. this.icoPause.destroy();
  36009. this.icoPause = null;
  36010. this.btnReset.destroy();
  36011. this.btnReset = null;
  36012. this.icoReset.destroy();
  36013. this.icoReset = null;
  36014. this.txtScore.destroy();
  36015. this.txtScore = null;
  36016. this.txtScoreValue.destroy();
  36017. this.txtScoreValue = null;
  36018. this.txtClicks.destroy();
  36019. this.txtClicks = null;
  36020. this.txtClicksValue.destroy();
  36021. this.txtClicksValue = null;
  36022. this.txtLevel.destroy();
  36023. this.txtLevel = null;
  36024. this.txtLevelValue.destroy();
  36025. this.txtLevelValue = null;
  36026. this.txtCombo.destroy();
  36027. this.txtCombo = null;
  36028. this.txtComboValue.destroy();
  36029. this.txtComboValue = null;
  36030. this.tlClicksValue.clear();
  36031. this.tlClicksValue = null;
  36032. /*this.btnWalkthrough.destroy();
  36033. this.btnWalkthrough = null;
  36034. this.icoWalkthrough.destroy();
  36035. this.icoWalkthrough = null;*/
  36036. /*this.spilLogo.destroy();
  36037. this.spilLogo = null;*/
  36038. };
  36039. Toolbar.prototype.onBtnPauseClick = function () {
  36040. if (this.app.playState.completeDlg.showed) return;
  36041. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  36042. this.app.playState.pauseDlg.show();
  36043. //this.app.playState.completeDlg.show();
  36044. };
  36045. Toolbar.prototype.onBtnResetClick = function () {
  36046. if (this.app.playState.completeDlg.showed) return;
  36047. if (this.app.isCanPlayAudio && this.app.isSound) this.app.buttonDownSound.play();
  36048. this.app.playState.reset();
  36049. };
  36050. Toolbar.prototype.onBtnWalkthroughClick = function () {
  36051. window.open('https://www.youtube.com/watch?v=VJVGHiQCOsQ', '_blank');
  36052. };
  36053. Toolbar.prototype.setScore = function (score) {
  36054. this.txtScoreValue.setText(score.toString());
  36055. };
  36056. Toolbar.prototype.setClicks = function (clicks) {
  36057. this.txtClicksValue.setText(clicks.toString());
  36058. };
  36059. Toolbar.prototype.setLevel = function (level) {
  36060. this.txtLevelValue.setText(level.toString());
  36061. };
  36062. Toolbar.prototype.setCombo = function (score) {
  36063. this.txtComboValue.visible = this.txtCombo.visible = true;
  36064. this.txtComboValue.setText('+' + score.toString());
  36065. };
  36066. Toolbar.prototype.hideCombo = function () {
  36067. this.txtComboValue.visible = this.txtCombo.visible = false;
  36068. this.txtComboValue.setText('');
  36069. };
  36070. Toolbar.prototype.bubblingClicks = function () {
  36071. this.tlClicksValue.restart();
  36072. };
  36073. /**
  36074. * User: qzix13
  36075. * Date: 15.12.13
  36076. */
  36077. function Bubble(app, col, row, sizeIndex) {
  36078. this.app = app;
  36079. this.initSizeIndex = this.sizeIndex = sizeIndex;
  36080. var cellSize = app.playState.cellSize;
  36081. var x = col * cellSize + cellSize / 2;
  36082. var y = row * cellSize + cellSize / 2;
  36083. var color = app.playState.bubbleColors[sizeIndex];
  36084. var size = app.playState.bubbleSizes[sizeIndex];
  36085. this.sprite = app.playState.bubblesGroup.create(x, y, 'game_atlas');
  36086. this.sprite.anchor.setTo(0.5, 0.5);
  36087. for (var i = sizeIndex; i < 4; i++) this.sprite.animations.add('blink_' + i, app.playState.bubbleBlinkAnim[i], 8, false);
  36088. this.sprite.play('blink_' + sizeIndex);
  36089. this.sprite.animations.stop();
  36090. this.sprite.body.immovable = true;
  36091. this.sprite.inputEnabled = true;
  36092. this.sprite.events.onInputDown.add(this.onDown, this);
  36093. this.sprite.self = this;
  36094. this.setSizeByIndex(sizeIndex);
  36095. var currScaleX = this.sprite.scale.x;
  36096. var currScaleY = this.sprite.scale.y;
  36097. this.bubbling = new TimelineLite();
  36098. this.bubbling.to(this.sprite.scale, 0.1, { x: currScaleX + .1, y: currScaleY - .1 } );
  36099. this.bubbling.to(this.sprite.scale, 0.1, { x: currScaleX - .1, y: currScaleY + .1 } );
  36100. this.bubbling.to(this.sprite.scale, 0.1, { x: currScaleX + .07, y: currScaleY - .07 } );
  36101. this.bubbling.to(this.sprite.scale, 0.1, { x: currScaleX - .07, y: currScaleY + .07 } );
  36102. this.bubbling.to(this.sprite.scale, 0.1, { x: currScaleX + .035, y: currScaleY - .035 } );
  36103. this.bubbling.to(this.sprite.scale, 0.1, { x: currScaleX - .035, y: currScaleY + .035 } );
  36104. this.bubbling.to(this.sprite.scale, 0.1, { x: currScaleX, y: currScaleY } );
  36105. this.bubbling.gotoAndStop(0.0);
  36106. this.popped = false;
  36107. this.destroyed = false;
  36108. app.playState.addBubble(this);
  36109. }
  36110. Bubble.prototype.destroy = function () {
  36111. this.destroyed = true;
  36112. this.app = null;
  36113. this.sprite.destroy();
  36114. this.sprite = null;
  36115. this.bubbling.clear();
  36116. this.bubbling = null;
  36117. this.popped = true;
  36118. };
  36119. /**
  36120. * Збільшити кульку.
  36121. * @param bullet Пуля, яка влучила. Може бути null, якщо користувач клікнув по кульці.
  36122. */
  36123. Bubble.prototype.grow = function (bullet) {
  36124. if (this.destroyed) return;
  36125. if (this.popped) {
  36126. if (bullet) bullet.continue();
  36127. return;
  36128. }
  36129. if (bullet) bullet.stop();
  36130. var index = ++this.sizeIndex;
  36131. if (index >= 4) this.pop();
  36132. else {
  36133. this.setColorByIndex(index);
  36134. this.setSizeByIndex(index);
  36135. this.bubbling.restart();
  36136. if (this.app.isCanPlayAudio && this.app.isSound) this.app.bubbleGrowSound.play();
  36137. }
  36138. };
  36139. Bubble.prototype.pop = function () {
  36140. if (this.destroyed) return;
  36141. if (this.popped) return;
  36142. this.popped = true;
  36143. this.sprite.exists = this.sprite.alive = false;
  36144. var _pop_ = function () {
  36145. if (this.destroyed) return;
  36146. this.sprite.visible = false;
  36147. this.app.playState.addRequest(function() {
  36148. if (this.destroyed) return;
  36149. this.sprite.group.remove(this.sprite);
  36150. }, this);
  36151. for (var i = 0; i < 4; i++) {
  36152. var bullet = this.app.playState.getBullet();
  36153. bullet.start(this.sprite.x, this.sprite.y, this.app.playState.bulletDirections[i]);
  36154. }
  36155. this.app.playState.addOnePoppedBubble();
  36156. if (this.app.isCanPlayAudio && this.app.isSound) this.app.bubblePopSound.play();
  36157. }
  36158. var s = this.app.playState.bulletSize;
  36159. TweenLite.to(this.sprite, 0.15, { width: s, height: s, onComplete: _pop_, onCompleteScope: this } );
  36160. };
  36161. Bubble.prototype.onDown = function () {
  36162. if (this.destroyed) return;
  36163. if (this.app.playState.subOneClick()) {
  36164. this.grow();
  36165. } else {
  36166. this.app.playState.toolbar.bubblingClicks();
  36167. }
  36168. };
  36169. Bubble.prototype.reset = function () {
  36170. if (this.destroyed) return;
  36171. TweenLite.killTweensOf(this.sprite);
  36172. var index = this.sizeIndex = this.initSizeIndex;
  36173. this.bubbling.gotoAndStop(0.0);
  36174. this.setColorByIndex(index, true);
  36175. this.setSizeByIndex(index);
  36176. this.sprite.visible = this.sprite.exists = this.sprite.alive = true;
  36177. this.popped = false;
  36178. this.app.playState.bubblesGroup.add(this.sprite);
  36179. };
  36180. Bubble.prototype.setColorByIndex = function (index, stopAnimation) {
  36181. if (this.destroyed) return;
  36182. if (stopAnimation === undefined) stopAnimation = false;
  36183. this.sprite.play('blink_' + index);
  36184. this.sprite.animations.stop(null, true);
  36185. };
  36186. Bubble.prototype.setSizeByIndex = function (index) {
  36187. if (this.destroyed) return;
  36188. var size = this.app.playState.bubbleSizes[index];
  36189. var color = this.app.playState.bubbleColors[index]
  36190. this.sprite.frameName = 'bubble_' + color + '_0001';
  36191. this.sprite.width = this.sprite.height = size;
  36192. this.sprite.body.setSize(size * 0.7, size * 0.7);
  36193. };
  36194. Bubble.prototype.makeBlinking = function () {
  36195. if (this.destroyed) return;
  36196. if (this.popped) return;
  36197. this.sprite.play('blink_' + this.sizeIndex);
  36198. };
  36199. /**
  36200. * User: qzix13
  36201. * Date: 18.12.13
  36202. */
  36203. function Bullet(app) {
  36204. this.app = app;
  36205. this.sprite = new Phaser.Sprite(app.phaser, 0, 0, 'game_atlas', 'bullet');
  36206. this.sprite.visible = this.sprite.exists = this.sprite.alive = false;
  36207. this.sprite.anchor.setTo(0.5, 0.5);
  36208. this.sprite.width = this.sprite.height = app.playState.bulletSize;
  36209. this.sprite.body.allowRotation = false;
  36210. this.sprite.body.allowGravity = false;
  36211. this.speed = 450;
  36212. this.initX = -1;
  36213. this.initY = -1;
  36214. this.sprite.self = this;
  36215. this.busy = false;
  36216. this.destroyed = false;
  36217. }
  36218. Bullet.prototype.destroy = function () {
  36219. this.destroyed = true;
  36220. this.busy = true;
  36221. this.app = null;
  36222. this.sprite.destroy();
  36223. this.sprite = null;
  36224. };
  36225. /**
  36226. * Запуск/перезапуск кульки.
  36227. * @param x Координата x
  36228. * @param y Координата y
  36229. * @param direction Напрямок руху (left|right|up|down)
  36230. */
  36231. Bullet.prototype.start = function (x, y, direction) {
  36232. if (this.destroyed) return;
  36233. if (this.busy) return;
  36234. this.busy = true;
  36235. this.initX = this.sprite.x = x;
  36236. this.initY = this.sprite.y = y;
  36237. this.direction = direction;
  36238. this.defineVel();
  36239. this.app.playState.addRequest(function() {
  36240. if (this.destroyed) return;
  36241. this.sprite.visible = this.sprite.exists = this.sprite.alive = true;
  36242. this.app.playState.bulletsGroup.add(this.sprite);
  36243. this.app.playState.addBullet(this);
  36244. }, this);
  36245. };
  36246. Bullet.prototype.pause = function () {
  36247. if (this.destroyed) return;
  36248. /*this.sprite.visible = */this.sprite.exists = this.sprite.alive = false;
  36249. this.sprite.body.velocity.setTo(0, 0);
  36250. };
  36251. Bullet.prototype.continue = function () {
  36252. if (this.destroyed) return;
  36253. /*this.sprite.visible = */this.sprite.exists = this.sprite.alive = true;
  36254. this.defineVel();
  36255. };
  36256. Bullet.prototype.stop = function () {
  36257. if (this.destroyed) return;
  36258. this.sprite.visible = this.sprite.exists = this.sprite.alive = false;
  36259. this.sprite.body.velocity.setTo(0, 0);
  36260. this.sprite.x = this.sprite.y = -100;
  36261. this.app.playState.addRequest(function() {
  36262. if (this.destroyed) return;
  36263. this.busy = false;
  36264. if (this.sprite.group) this.sprite.group.remove(this.sprite);
  36265. this.app.playState.addBulletInCache(this);
  36266. }, this);
  36267. };
  36268. Bullet.prototype.defineVel = function () {
  36269. if (this.destroyed) return;
  36270. if (this.direction == 'left') this.sprite.body.velocity.setTo(-this.speed, 0);
  36271. else if (this.direction == 'right') this.sprite.body.velocity.setTo(this.speed, 0);
  36272. else if (this.direction == 'up') this.sprite.body.velocity.setTo(0, -this.speed);
  36273. else if (this.direction == 'down') this.sprite.body.velocity.setTo(0, this.speed);
  36274. };
  36275. /**
  36276. * User: qzix13
  36277. * Date: 11.12.13
  36278. */
  36279. (function () {
  36280. var app = {
  36281. phaser: null,
  36282. menuState: null,
  36283. playState: null,
  36284. levelMng: null,
  36285. bgOver: null,
  36286. score: [],
  36287. originSizes: {
  36288. width: 640,
  36289. height: 960,
  36290. gameWidth: 640,
  36291. gameHeight: 712,
  36292. },
  36293. fitSizes: {
  36294. width: null,
  36295. height: null,
  36296. gameWidth: null,
  36297. gameHeight: null,
  36298. },
  36299. scale: 1.0,
  36300. reqWidth: null,
  36301. reqHeight: null,
  36302. isCanPlayAudio: true,
  36303. isSound: false,
  36304. isMusic: false,
  36305. buttonDownSound: null,
  36306. bubbleGrowSound: null,
  36307. bubblePopSound: null,
  36308. levelCompleteSound: null,
  36309. mainThemeSound: null,
  36310. isPaused: false,
  36311. lang: '',
  36312. texts: null,
  36313. gotoSponsor: function () { SG.redirectToPortal(); },
  36314. createMenuState: function () { this.menuState = new MenuState(this); resizeGame(); this.menuState.resize(); },
  36315. createPlayState: function () { this.playState = new PlayState(this); resizeGame(); this.playState.resize(); },
  36316. saveScore: function (level, score) {
  36317. level--;
  36318. if (this.score[level] < score) {
  36319. this.score[level] = score;
  36320. cookie.set('s' + level, score);
  36321. }
  36322. },
  36323. getTotalScore: function () {
  36324. var s = 0;
  36325. for (var i = 0; i < 30; i++) {
  36326. s += this.score[i];
  36327. }
  36328. return s;
  36329. },
  36330. mute: function () {
  36331. if (this.isCanPlayAudio && this.isMusic && this.mainThemeSound) {
  36332. this.mainThemeSound.stop();
  36333. this.isMusic = false;
  36334. if (this.menuState) this.menuState.refreshBtns();
  36335. if (this.playState) this.playState.pauseDlg.refreshBtns();
  36336. }
  36337. },
  36338. unmute: function () {
  36339. if (this.isCanPlayAudio && this.isMusic === false && this.mainThemeSound) {
  36340. this.isMusic = true;
  36341. this.mainThemeSound.stop();
  36342. this.mainThemeSound.play('', 0, 1, true, true);
  36343. if (this.menuState) this.menuState.refreshBtns();
  36344. if (this.playState) this.playState.pauseDlg.refreshBtns();
  36345. }
  36346. },
  36347. pause: function () {
  36348. this.isPaused = true;
  36349. if (this.mainThemeSound) {
  36350. this.mainThemeSound.stop();
  36351. }
  36352. if (this.playState) {
  36353. if (this.playState.completeDlgGroup.visible === false) {
  36354. this.playState.pauseDlgGroup.visible = true;
  36355. this.playState.pause(true);
  36356. }
  36357. }
  36358. },
  36359. resume: function () {
  36360. this.isPaused = false;
  36361. if (this.mainThemeSound) {
  36362. this.mainThemeSound.stop();
  36363. if (this.isMusic && !this.mainThemeSound.pendingPlayback) this.mainThemeSound.play('', 0, 1, true, true);
  36364. }
  36365. },
  36366. unpause: function () {
  36367. this.resume();
  36368. if (this.playState) {
  36369. if (this.playState.completeDlgGroup.visible === false) {
  36370. this.playState.pauseDlgGroup.visible = false;
  36371. this.playState.pause(false);
  36372. }
  36373. }
  36374. },
  36375. resetGame: function () {
  36376. if (this.playState) this.playState.destroy();
  36377. if (!this.menuState) this.createMenuState();
  36378. this.menuState.onBtnClearYesClick();
  36379. if (this.isCanPlayAudio && this.isMusic && this.mainThemeSound) {
  36380. this.mainThemeSound.stop();
  36381. this.mainThemeSound.play('', 0, this.isMusic ? 1 : 0, true);
  36382. }
  36383. }
  36384. };
  36385. setTimeout("window.scrollTo(0, 1)", 10);
  36386. window.blastballApp = app;
  36387. var txtLoadingValue = null;
  36388. var picRotatePhone = null;
  36389. resizeGame();
  36390. window.addEventListener('resize', resizeGame, false);
  36391. window.addEventListener('orientationchange', resizeGame, false);
  36392. app.phaser = new Phaser.Game(app.originSizes.width, app.originSizes.height, Phaser.CANVAS, 'gameArea',
  36393. { preload: preload, loadUpdate: loadUpdate, create: create, update: update/*, render: render*/ } );
  36394. function resizeGame(width, height) {
  36395. var screenWidth, screenHeight;
  36396. if (typeof width === 'number' && typeof height === 'number') {
  36397. screenWidth = width;
  36398. screenHeight = height;
  36399. } else if (app.reqWidth && app.reqHeight) {
  36400. screenWidth = app.reqWidth;
  36401. screenHeight = app.reqHeight;
  36402. if (app.fitSizes.width === screenWidth && app.fitSizes.height === screenHeight) return;
  36403. } else {
  36404. screenWidth = window.innerWidth;
  36405. screenHeight = window.innerHeight;
  36406. }
  36407. var width = app.originSizes.width;
  36408. var height = app.originSizes.height;
  36409. var gameWidth = app.originSizes.gameWidth;
  36410. var gameHeight = app.originSizes.gameHeight;
  36411. var gameSize = calcScreenFit(gameWidth / gameHeight, screenWidth, screenHeight);
  36412. app.fitSizes.width = width *= gameSize.width / gameWidth;
  36413. app.fitSizes.height = height *= gameSize.height / gameHeight;
  36414. if (app.fitSizes.width > screenWidth) app.fitSizes.width = width = screenWidth;
  36415. if (app.fitSizes.height > screenHeight) app.fitSizes.height = height = screenHeight;
  36416. app.fitSizes.gameWidth = gameSize.width;
  36417. app.fitSizes.gameHeight = gameSize.height;
  36418. app.scale = app.fitSizes.gameWidth / app.originSizes.gameWidth;
  36419. var gameArea = document.getElementById('gameArea');
  36420. gameArea.style.width = width + 'px';
  36421. gameArea.style.height = height + 'px';
  36422. gameArea.style.marginLeft = (window.innerWidth / 2 - width / 2) + 'px';
  36423. gameArea.style.marginTop = 0;//(window.innerHeight / 2 - height / 2) + 'px';
  36424. if (app.phaser) {
  36425. app.phaser.width = width;
  36426. app.phaser.height = height;
  36427. app.phaser.stage.bounds.width = app.phaser.width;
  36428. app.phaser.stage.bounds.height = app.phaser.height;
  36429. app.phaser.renderer.resize(app.phaser.width, app.phaser.height);
  36430. }
  36431. if (app.bgOver) {
  36432. app.bgOver.x = (app.fitSizes.width - 540 * app.scale) / 2;
  36433. app.bgOver.y = (app.fitSizes.height - 704 * app.scale) / 2;
  36434. app.bgOver.scale.x = app.bgOver.scale.y = app.scale;
  36435. //app.bgOver.y = (app.fitSizes.height - 960 * app.scale) / 2;
  36436. }
  36437. if (app.menuState) app.menuState.resize();
  36438. if (app.playState) app.playState.resize();
  36439. if (txtLoadingValue) {
  36440. txtLoadingValue.scale.setTo(.9 * app.scale, .9 * app.scale);
  36441. txtLoadingValue.x = app.fitSizes.width / 2;
  36442. txtLoadingValue.y = app.fitSizes.height / 2 - 20 * app.scale;
  36443. }
  36444. if ((app.playState || app.menuState) && window.orientation != undefined) {
  36445. if (picRotatePhone == null && app.phaser) {
  36446. picRotatePhone = app.phaser.add.sprite(app.fitSizes.width / 2, app.fitSizes.height / 2, 'rotate_phone');
  36447. picRotatePhone.anchor.setTo(0.5, 0.5);
  36448. picRotatePhone.visible = false;
  36449. }
  36450. if (picRotatePhone) {
  36451. var portrait = Math.abs(parseInt(window.orientation)) != 90;
  36452. picRotatePhone.x = app.fitSizes.width / 2;
  36453. picRotatePhone.y = app.fitSizes.height / 2;
  36454. //picRotatePhone.width = 242 * app.scale * 2;
  36455. //picRotatePhone.height = 305 * app.scale * 2;
  36456. picRotatePhone.scale.setTo(app.scale * 1.4, app.scale * 1.4);
  36457. if (app.playState) app.playState.canvas.visible = portrait;
  36458. if (app.menuState) app.menuState.canvas.visible = portrait;
  36459. picRotatePhone.visible = !portrait;
  36460. }
  36461. }
  36462. //if (app.phaser) console.log(app.phaser._paused);
  36463. //if (app.fpsText) app.phaser.world.bringToTop(app.fpsText);
  36464. }
  36465. app.resizeGame = resizeGame;
  36466. SG_Hooks.setOrientationHandler(resizeGame);
  36467. SG_Hooks.setResizeHandler(resizeGame);
  36468. function preload() {
  36469. app.lang = SG.lang //SG_Hooks.getLanguage(['en', 'es']);
  36470. app.phaser.load.image('rotate_phone', 'assets/images/rotate_phone_' + app.lang + '.png');
  36471. app.phaser.load.bitmapFont('hobo_digits', 'assets/fonts/hobo_digits.png', 'assets/fonts/hobo_digits.fnt')
  36472. app.phaser.load.onFileComplete.add(onFileComplete);
  36473. var ext = (app.phaser.device.iOS || app.phaser.device.macOS) ? 'm4a' : 'ogg';
  36474. app.phaser.load.audio('bubble_grow', 'assets/sounds/' + ext + '/bubble_grow.' + ext);
  36475. app.phaser.load.audio('bubble_pop', 'assets/sounds/' + ext + '/bubble_pop.' + ext);
  36476. app.phaser.load.audio('button_click', 'assets/sounds/' + ext + '/button_click.' + ext);
  36477. app.phaser.load.audio('level_complete', 'assets/sounds/' + ext + '/level_complete.' + ext);
  36478. app.phaser.load.audio('level_failed', 'assets/sounds/' + ext + '/level_failed.' + ext);
  36479. app.phaser.load.audio('main_theme', 'assets/sounds/' + ext + '/main_theme.' + ext);
  36480. var txtAtlas = "atlas_txt_" + app.lang;
  36481. app.phaser.load.text('texts', 'assets/localization/' + app.lang + '.json');
  36482. app.phaser.load.atlasXML('txt_atlas', 'assets/images/' + txtAtlas + '.png', 'assets/images/' + txtAtlas +'.xml');
  36483. app.phaser.load.image('bg_clear', 'assets/images/bg_clear_' + app.lang + '.png');
  36484. app.phaser.load.spritesheet('button_more_games', 'assets/images/button_more_games_sheet_' + app.lang + '.png', 250, 100);
  36485. app.phaser.load.atlasXML('game_atlas', 'assets/images/game_atlas.png', 'assets/images/game_atlas.xml');
  36486. app.phaser.load.image('flowers', 'assets/images/flowers.png');
  36487. app.phaser.load.image('bg', 'assets/images/bg.png');
  36488. app.phaser.load.image('bg_pause', 'assets/images/bg_pause.png');
  36489. app.phaser.load.image('bg_complete', 'assets/images/bg_complete.png');
  36490. app.phaser.load.image('bg_credits', 'assets/images/bg_credits.png');
  36491. app.phaser.load.image('game_name', 'assets/images/game_name.png');
  36492. app.phaser.load.spritesheet('button_play', 'assets/images/button_play_sheet.png', 160, 160);
  36493. app.phaser.load.bitmapFont('hobo_text', 'assets/fonts/hobo_text.png', 'assets/fonts/hobo_text.fnt');
  36494. }
  36495. function onFileComplete(progress, key, success, totalLoadedFiles, fileListLength) {
  36496. var x = app.fitSizes.width / 2;
  36497. var y = app.fitSizes.height / 2;
  36498. if (key === 'hobo_digits') {
  36499. txtLoadingValue = app.phaser.add.bitmapText(x, y - 30 * app.scale, '0%', { font: '32px HoboDigits', align: 'center' });
  36500. txtLoadingValue.anchor.setTo(.5, .5);
  36501. //txtLoadingValue.scale.setTo(.9 * app.scale, .9 * app.scale);
  36502. app.phaser.load.onFileComplete.remove(onFileComplete);
  36503. }
  36504. resizeGame();
  36505. }
  36506. function loadUpdate() {
  36507. if (txtLoadingValue) txtLoadingValue.setText(app.phaser.load.progress + '%');
  36508. }
  36509. function create() {
  36510. app.phaser.onPause.add(app.pause, app);
  36511. app.phaser.onResume.add(app.resume, app);
  36512. txtLoadingValue.setText('100%');
  36513. app.isCanPlayAudio = app.phaser.device.canPlayAudio('ogg') || app.phaser.device.canPlayAudio('m4a');
  36514. TweenLite.delayedCall(app.isCanPlayAudio ? 0.2 : 1.0, function() {
  36515. for (var i = 0; i < 30; i++) {
  36516. var score = parseInt(cookie.get('s' + i));
  36517. if (score) app.score[i] = score;
  36518. else app.score[i] = 0;
  36519. }
  36520. txtLoadingValue.visible = false;
  36521. /*spilLogoL.loadTexture('splash');
  36522. spilLogoL.x = app.fitSizes.width / 2;
  36523. spilLogoL.y = app.fitSizes.height / 2;*/
  36524. //resizeGame();
  36525. if (app.isCanPlayAudio) {
  36526. app.buttonDownSound = app.phaser.add.audio('button_click');
  36527. app.bubbleGrowSound = app.phaser.add.audio('bubble_grow');
  36528. app.bubblePopSound = app.phaser.add.audio('bubble_pop');
  36529. app.levelCompleteSound = app.phaser.add.audio('level_complete');
  36530. app.levelFailedSound = app.phaser.add.audio('level_failed');
  36531. app.mainThemeSound = app.phaser.add.audio('main_theme');
  36532. app.mainThemeSound.play('', 0, app.isMusic ? 1 : 0, true);
  36533. }
  36534. /*setTimeout(function () { */run(); /*}, 3000);*/
  36535. });
  36536. }
  36537. function run() {
  36538. app.texts = JSON.parse(app.phaser.cache.getText('texts'));
  36539. app.bgOver = app.phaser.add.group(this.canvas);
  36540. //app.bgOver.create(0, 0, 'game_atlas', 'bg_over_left');
  36541. //app.bgOver.create(0, 0, 'game_atlas', 'bg_over_top');
  36542. //app.bgOver.create(0, 700, 'game_atlas', 'bg_over_top');
  36543. //app.bgOver.create(536, 0, 'game_atlas', 'bg_over_left');
  36544. app.levelMng = new LevelMng(app);
  36545. app.createMenuState();
  36546. //app.createPlayState();
  36547. /*app.fpsText = app.phaser.add.text(10, 10, "FPS: 60", { font: '20px Verdana', fill: '#ffffff', align: 'left' });
  36548. app.phaser.world.add(app.fpsText);*/
  36549. resizeGame();
  36550. txtLoadingValue.destroy();
  36551. txtLoadingValue = null;
  36552. SG_Hooks.start();
  36553. }
  36554. function update() {
  36555. if (app.playState) {
  36556. app.playState.update();
  36557. }
  36558. //if (app.fpsText) app.fpsText.setText(app.phaser.time.fps);
  36559. }
  36560. /*function render() {
  36561. app.phaser.debug.line('orientation :' + picRotatePhone, 10, 10);
  36562. }*/
  36563. function calcScreenFit(aspectRatio, screenW, screenH, isCentering) {
  36564. isCentering = isCentering == undefined ? false : true;
  36565. var width = screenW;
  36566. var height = screenH;
  36567. // Тільки одному всесвіту відомо як воно працює!!!
  36568. if (aspectRatio < 1 && screenW >= screenH) {
  36569. width = Math.floor(screenH * aspectRatio);
  36570. } else if (aspectRatio >= 1 && screenW <= screenH) {
  36571. height = Math.floor(screenW / aspectRatio);
  36572. } else {
  36573. if (Math.floor(screenH * aspectRatio) > screenW) height = screenW / aspectRatio;
  36574. else width = Math.floor(screenH * aspectRatio);
  36575. }
  36576. if (isCentering) return { x: (screenW - width) / 2, y: (screenH - height) / 2, width: width, height: height };
  36577. return {x: 0, y: 0, width: width, height: height };
  36578. }
  36579. /*function openURL(url){
  36580. var _a=document.createElement("a");
  36581. _a.href=url;
  36582. _a.target="_blank";
  36583. var _div=document.getElementById("gm4html5_div_id");
  36584. document.body.insertBefore(_a,_div);
  36585. _a.click();
  36586. }*/
  36587. }) ();